babylon.max.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054
  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. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = 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.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. 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);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. 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);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = Vector3.Normalize(axis1);
  870. var w = Vector3.Normalize(axis3);
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross;
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1;
  890. var v1;
  891. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  892. z = 1.0;
  893. }
  894. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  895. x = 1.0;
  896. }
  897. else {
  898. t = w.z / w.x;
  899. x = -t * Math.sqrt(1 / (1 + t * t));
  900. z = Math.sqrt(1 / (1 + t * t));
  901. }
  902. u1 = new Vector3(x, y, z);
  903. u1.normalize();
  904. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  905. v1.normalize();
  906. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  907. cross.normalize();
  908. if (Vector3.Dot(w, cross) < 0) {
  909. sign = 1.0;
  910. }
  911. dot = Vector3.Dot(u, u1);
  912. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  913. roll = Math.acos(dot) * sign;
  914. if (Vector3.Dot(u1, X) < 0) {
  915. roll = Math.PI + roll;
  916. u1 = u1.scaleInPlace(-1);
  917. v1 = v1.scaleInPlace(-1);
  918. nbRevert++;
  919. }
  920. // step 2 : rotate around u1
  921. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  922. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  923. var w2;
  924. var v2;
  925. x = 0.0;
  926. y = 0.0;
  927. z = 0.0;
  928. sign = -1;
  929. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  930. x = 1.0;
  931. }
  932. else {
  933. t = u1.z / u1.x;
  934. x = -t * Math.sqrt(1 / (1 + t * t));
  935. z = Math.sqrt(1 / (1 + t * t));
  936. }
  937. w2 = new Vector3(x, y, z);
  938. w2.normalize();
  939. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. v2 = v2.scaleInPlace(-1);
  952. w2 = w2.scaleInPlace(-1);
  953. nbRevert++;
  954. }
  955. // step 3 : rotate around v2
  956. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  957. sign = -1;
  958. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  959. cross.normalize();
  960. if (Vector3.Dot(cross, Y) < 0) {
  961. sign = 1.0;
  962. }
  963. dot = Vector3.Dot(u1, X);
  964. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  965. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  966. if (dot < 0 && nbRevert < 2) {
  967. yaw = Math.PI + yaw;
  968. }
  969. ref.x = pitch;
  970. ref.y = yaw;
  971. ref.z = roll;
  972. };
  973. return Vector3;
  974. })();
  975. BABYLON.Vector3 = Vector3;
  976. //Vector4 class created for EulerAngle class conversion to Quaternion
  977. var Vector4 = (function () {
  978. function Vector4(x, y, z, w) {
  979. this.x = x;
  980. this.y = y;
  981. this.z = z;
  982. this.w = w;
  983. }
  984. Vector4.prototype.toString = function () {
  985. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  986. };
  987. // Operators
  988. Vector4.prototype.asArray = function () {
  989. var result = [];
  990. this.toArray(result, 0);
  991. return result;
  992. };
  993. Vector4.prototype.toArray = function (array, index) {
  994. if (index === undefined) {
  995. index = 0;
  996. }
  997. array[index] = this.x;
  998. array[index + 1] = this.y;
  999. array[index + 2] = this.z;
  1000. array[index + 3] = this.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.addInPlace = function (otherVector) {
  1004. this.x += otherVector.x;
  1005. this.y += otherVector.y;
  1006. this.z += otherVector.z;
  1007. this.w += otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.add = function (otherVector) {
  1011. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1012. };
  1013. Vector4.prototype.addToRef = function (otherVector, result) {
  1014. result.x = this.x + otherVector.x;
  1015. result.y = this.y + otherVector.y;
  1016. result.z = this.z + otherVector.z;
  1017. result.w = this.w + otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractInPlace = function (otherVector) {
  1021. this.x -= otherVector.x;
  1022. this.y -= otherVector.y;
  1023. this.z -= otherVector.z;
  1024. this.w -= otherVector.w;
  1025. return this;
  1026. };
  1027. Vector4.prototype.subtract = function (otherVector) {
  1028. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1029. };
  1030. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1031. result.x = this.x - otherVector.x;
  1032. result.y = this.y - otherVector.y;
  1033. result.z = this.z - otherVector.z;
  1034. result.w = this.w - otherVector.w;
  1035. return this;
  1036. };
  1037. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1038. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1039. };
  1040. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1041. result.x = this.x - x;
  1042. result.y = this.y - y;
  1043. result.z = this.z - z;
  1044. result.w = this.w - w;
  1045. return this;
  1046. };
  1047. Vector4.prototype.negate = function () {
  1048. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1049. };
  1050. Vector4.prototype.scaleInPlace = function (scale) {
  1051. this.x *= scale;
  1052. this.y *= scale;
  1053. this.z *= scale;
  1054. this.w *= scale;
  1055. return this;
  1056. };
  1057. Vector4.prototype.scale = function (scale) {
  1058. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1059. };
  1060. Vector4.prototype.scaleToRef = function (scale, result) {
  1061. result.x = this.x * scale;
  1062. result.y = this.y * scale;
  1063. result.z = this.z * scale;
  1064. result.w = this.w * scale;
  1065. };
  1066. Vector4.prototype.equals = function (otherVector) {
  1067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1068. };
  1069. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1070. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1071. return otherVector
  1072. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1074. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1075. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1076. };
  1077. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1078. return this.x === x && this.y === y && this.z === z && this.w === w;
  1079. };
  1080. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1081. this.x *= otherVector.x;
  1082. this.y *= otherVector.y;
  1083. this.z *= otherVector.z;
  1084. this.w *= otherVector.w;
  1085. return this;
  1086. };
  1087. Vector4.prototype.multiply = function (otherVector) {
  1088. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1089. };
  1090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1091. result.x = this.x * otherVector.x;
  1092. result.y = this.y * otherVector.y;
  1093. result.z = this.z * otherVector.z;
  1094. result.w = this.w * otherVector.w;
  1095. return this;
  1096. };
  1097. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1098. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1099. };
  1100. Vector4.prototype.divide = function (otherVector) {
  1101. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1102. };
  1103. Vector4.prototype.divideToRef = function (otherVector, result) {
  1104. result.x = this.x / otherVector.x;
  1105. result.y = this.y / otherVector.y;
  1106. result.z = this.z / otherVector.z;
  1107. result.w = this.w / otherVector.w;
  1108. return this;
  1109. };
  1110. Vector4.prototype.MinimizeInPlace = function (other) {
  1111. if (other.x < this.x)
  1112. this.x = other.x;
  1113. if (other.y < this.y)
  1114. this.y = other.y;
  1115. if (other.z < this.z)
  1116. this.z = other.z;
  1117. if (other.w < this.w)
  1118. this.w = other.w;
  1119. return this;
  1120. };
  1121. Vector4.prototype.MaximizeInPlace = function (other) {
  1122. if (other.x > this.x)
  1123. this.x = other.x;
  1124. if (other.y > this.y)
  1125. this.y = other.y;
  1126. if (other.z > this.z)
  1127. this.z = other.z;
  1128. if (other.w > this.w)
  1129. this.w = other.w;
  1130. return this;
  1131. };
  1132. // Properties
  1133. Vector4.prototype.length = function () {
  1134. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1135. };
  1136. Vector4.prototype.lengthSquared = function () {
  1137. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1138. };
  1139. // Methods
  1140. Vector4.prototype.normalize = function () {
  1141. var len = this.length();
  1142. if (len === 0)
  1143. return this;
  1144. var num = 1.0 / len;
  1145. this.x *= num;
  1146. this.y *= num;
  1147. this.z *= num;
  1148. this.w *= num;
  1149. return this;
  1150. };
  1151. Vector4.prototype.clone = function () {
  1152. return new Vector4(this.x, this.y, this.z, this.w);
  1153. };
  1154. Vector4.prototype.copyFrom = function (source) {
  1155. this.x = source.x;
  1156. this.y = source.y;
  1157. this.z = source.z;
  1158. this.w = source.w;
  1159. return this;
  1160. };
  1161. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1162. this.x = x;
  1163. this.y = y;
  1164. this.z = z;
  1165. this.w = w;
  1166. return this;
  1167. };
  1168. // Statics
  1169. Vector4.FromArray = function (array, offset) {
  1170. if (!offset) {
  1171. offset = 0;
  1172. }
  1173. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1174. };
  1175. Vector4.FromArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1182. result.x = array[offset];
  1183. result.y = array[offset + 1];
  1184. result.z = array[offset + 2];
  1185. result.w = array[offset + 3];
  1186. };
  1187. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1188. result.x = x;
  1189. result.y = y;
  1190. result.z = z;
  1191. result.w = w;
  1192. };
  1193. Vector4.Zero = function () {
  1194. return new Vector4(0, 0, 0, 0);
  1195. };
  1196. Vector4.Normalize = function (vector) {
  1197. var result = Vector4.Zero();
  1198. Vector4.NormalizeToRef(vector, result);
  1199. return result;
  1200. };
  1201. Vector4.NormalizeToRef = function (vector, result) {
  1202. result.copyFrom(vector);
  1203. result.normalize();
  1204. };
  1205. Vector4.Minimize = function (left, right) {
  1206. var min = left.clone();
  1207. min.MinimizeInPlace(right);
  1208. return min;
  1209. };
  1210. Vector4.Maximize = function (left, right) {
  1211. var max = left.clone();
  1212. max.MaximizeInPlace(right);
  1213. return max;
  1214. };
  1215. Vector4.Distance = function (value1, value2) {
  1216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1217. };
  1218. Vector4.DistanceSquared = function (value1, value2) {
  1219. var x = value1.x - value2.x;
  1220. var y = value1.y - value2.y;
  1221. var z = value1.z - value2.z;
  1222. var w = value1.w - value2.w;
  1223. return (x * x) + (y * y) + (z * z) + (w * w);
  1224. };
  1225. Vector4.Center = function (value1, value2) {
  1226. var center = value1.add(value2);
  1227. center.scaleInPlace(0.5);
  1228. return center;
  1229. };
  1230. return Vector4;
  1231. })();
  1232. BABYLON.Vector4 = Vector4;
  1233. var Quaternion = (function () {
  1234. function Quaternion(x, y, z, w) {
  1235. if (x === void 0) { x = 0; }
  1236. if (y === void 0) { y = 0; }
  1237. if (z === void 0) { z = 0; }
  1238. if (w === void 0) { w = 1; }
  1239. this.x = x;
  1240. this.y = y;
  1241. this.z = z;
  1242. this.w = w;
  1243. }
  1244. Quaternion.prototype.toString = function () {
  1245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1246. };
  1247. Quaternion.prototype.asArray = function () {
  1248. return [this.x, this.y, this.z, this.w];
  1249. };
  1250. Quaternion.prototype.equals = function (otherQuaternion) {
  1251. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1252. };
  1253. Quaternion.prototype.clone = function () {
  1254. return new Quaternion(this.x, this.y, this.z, this.w);
  1255. };
  1256. Quaternion.prototype.copyFrom = function (other) {
  1257. this.x = other.x;
  1258. this.y = other.y;
  1259. this.z = other.z;
  1260. this.w = other.w;
  1261. return this;
  1262. };
  1263. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1264. this.x = x;
  1265. this.y = y;
  1266. this.z = z;
  1267. this.w = w;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.add = function (other) {
  1271. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1272. };
  1273. Quaternion.prototype.subtract = function (other) {
  1274. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1275. };
  1276. Quaternion.prototype.scale = function (value) {
  1277. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1278. };
  1279. Quaternion.prototype.multiply = function (q1) {
  1280. var result = new Quaternion(0, 0, 0, 1.0);
  1281. this.multiplyToRef(q1, result);
  1282. return result;
  1283. };
  1284. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1285. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1286. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1287. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1288. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1289. result.copyFromFloats(x, y, z, w);
  1290. return this;
  1291. };
  1292. Quaternion.prototype.multiplyInPlace = function (q1) {
  1293. this.multiplyToRef(q1, this);
  1294. return this;
  1295. };
  1296. Quaternion.prototype.length = function () {
  1297. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1298. };
  1299. Quaternion.prototype.normalize = function () {
  1300. var length = 1.0 / this.length();
  1301. this.x *= length;
  1302. this.y *= length;
  1303. this.z *= length;
  1304. this.w *= length;
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toEulerAngles = function () {
  1308. var result = Vector3.Zero();
  1309. this.toEulerAnglesToRef(result);
  1310. return result;
  1311. };
  1312. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1313. //result is an EulerAngles in the in the z-x-z convention
  1314. var qx = this.x;
  1315. var qy = this.y;
  1316. var qz = this.z;
  1317. var qw = this.w;
  1318. var qxy = qx * qy;
  1319. var qxz = qx * qz;
  1320. var qwy = qw * qy;
  1321. var qwz = qw * qz;
  1322. var qwx = qw * qx;
  1323. var qyz = qy * qz;
  1324. var sqx = qx * qx;
  1325. var sqy = qy * qy;
  1326. var determinant = sqx + sqy;
  1327. if (determinant !== 0.000 && determinant !== 1.000) {
  1328. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1329. result.y = Math.acos(1 - 2 * determinant);
  1330. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1331. }
  1332. else {
  1333. if (determinant === 0.0) {
  1334. result.x = 0.0;
  1335. result.y = 0.0;
  1336. 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)
  1337. }
  1338. else {
  1339. 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)
  1340. result.y = Math.PI;
  1341. result.z = 0.0;
  1342. }
  1343. }
  1344. return this;
  1345. };
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. 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));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. 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]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. 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);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. 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);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. 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);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * 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
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. 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);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. 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)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. 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;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. 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)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. })(BABYLON || (BABYLON = {}));
  2955. var BABYLON;
  2956. (function (BABYLON) {
  2957. var Database = (function () {
  2958. function Database(urlToScene, callbackManifestChecked) {
  2959. // Handling various flavors of prefixed version of IndexedDB
  2960. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2961. this.callbackManifestChecked = callbackManifestChecked;
  2962. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2963. this.db = null;
  2964. this.enableSceneOffline = false;
  2965. this.enableTexturesOffline = false;
  2966. this.manifestVersionFound = 0;
  2967. this.mustUpdateRessources = false;
  2968. this.hasReachedQuota = false;
  2969. if (!Database.IDBStorageEnabled) {
  2970. this.callbackManifestChecked(true);
  2971. }
  2972. else {
  2973. this.checkManifestFile();
  2974. }
  2975. }
  2976. Database.prototype.checkManifestFile = function () {
  2977. var _this = this;
  2978. function noManifestFile() {
  2979. that.enableSceneOffline = false;
  2980. that.enableTexturesOffline = false;
  2981. that.callbackManifestChecked(false);
  2982. }
  2983. var that = this;
  2984. var manifestURL = this.currentSceneUrl + ".manifest";
  2985. var xhr = new XMLHttpRequest();
  2986. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2987. xhr.open("GET", manifestURLTimeStamped, true);
  2988. xhr.addEventListener("load", function () {
  2989. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2990. try {
  2991. var manifestFile = JSON.parse(xhr.response);
  2992. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2993. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2994. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2995. _this.manifestVersionFound = manifestFile.version;
  2996. }
  2997. if (_this.callbackManifestChecked) {
  2998. _this.callbackManifestChecked(true);
  2999. }
  3000. }
  3001. catch (ex) {
  3002. noManifestFile();
  3003. }
  3004. }
  3005. else {
  3006. noManifestFile();
  3007. }
  3008. }, false);
  3009. xhr.addEventListener("error", function (event) {
  3010. noManifestFile();
  3011. }, false);
  3012. try {
  3013. xhr.send();
  3014. }
  3015. catch (ex) {
  3016. BABYLON.Tools.Error("Error on XHR send request.");
  3017. that.callbackManifestChecked(false);
  3018. }
  3019. };
  3020. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3021. var _this = this;
  3022. function handleError() {
  3023. that.isSupported = false;
  3024. if (errorCallback)
  3025. errorCallback();
  3026. }
  3027. var that = this;
  3028. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3029. // Your browser doesn't support IndexedDB
  3030. this.isSupported = false;
  3031. if (errorCallback)
  3032. errorCallback();
  3033. }
  3034. else {
  3035. // If the DB hasn't been opened or created yet
  3036. if (!this.db) {
  3037. this.hasReachedQuota = false;
  3038. this.isSupported = true;
  3039. var request = this.idbFactory.open("babylonjs", 1);
  3040. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3041. request.onerror = function (event) {
  3042. handleError();
  3043. };
  3044. // executes when a version change transaction cannot complete due to other active transactions
  3045. request.onblocked = function (event) {
  3046. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3047. handleError();
  3048. };
  3049. // DB has been opened successfully
  3050. request.onsuccess = function (event) {
  3051. _this.db = request.result;
  3052. successCallback();
  3053. };
  3054. // Initialization of the DB. Creating Scenes & Textures stores
  3055. request.onupgradeneeded = function (event) {
  3056. _this.db = (event.target).result;
  3057. try {
  3058. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3059. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3060. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3061. }
  3062. catch (ex) {
  3063. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3064. handleError();
  3065. }
  3066. };
  3067. }
  3068. else {
  3069. if (successCallback)
  3070. successCallback();
  3071. }
  3072. }
  3073. };
  3074. Database.prototype.loadImageFromDB = function (url, image) {
  3075. var _this = this;
  3076. var completeURL = Database.ReturnFullUrlLocation(url);
  3077. var saveAndLoadImage = function () {
  3078. if (!_this.hasReachedQuota && _this.db !== null) {
  3079. // the texture is not yet in the DB, let's try to save it
  3080. _this._saveImageIntoDBAsync(completeURL, image);
  3081. }
  3082. else {
  3083. image.src = url;
  3084. }
  3085. };
  3086. if (!this.mustUpdateRessources) {
  3087. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3088. }
  3089. else {
  3090. saveAndLoadImage();
  3091. }
  3092. };
  3093. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3094. if (this.isSupported && this.db !== null) {
  3095. var texture;
  3096. var transaction = this.db.transaction(["textures"]);
  3097. transaction.onabort = function (event) {
  3098. image.src = url;
  3099. };
  3100. transaction.oncomplete = function (event) {
  3101. var blobTextureURL;
  3102. if (texture) {
  3103. var URL = window.URL || window.webkitURL;
  3104. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3105. image.onerror = function () {
  3106. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3107. image.src = url;
  3108. };
  3109. image.src = blobTextureURL;
  3110. }
  3111. else {
  3112. notInDBCallback();
  3113. }
  3114. };
  3115. var getRequest = transaction.objectStore("textures").get(url);
  3116. getRequest.onsuccess = function (event) {
  3117. texture = (event.target).result;
  3118. };
  3119. getRequest.onerror = function (event) {
  3120. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3121. image.src = url;
  3122. };
  3123. }
  3124. else {
  3125. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3126. image.src = url;
  3127. }
  3128. };
  3129. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3130. var _this = this;
  3131. if (this.isSupported) {
  3132. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3133. var generateBlobUrl = function () {
  3134. var blobTextureURL;
  3135. if (blob) {
  3136. var URL = window.URL || window.webkitURL;
  3137. try {
  3138. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3139. }
  3140. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3141. catch (ex) {
  3142. blobTextureURL = URL.createObjectURL(blob);
  3143. }
  3144. }
  3145. image.src = blobTextureURL;
  3146. };
  3147. if (Database.IsUASupportingBlobStorage) {
  3148. var xhr = new XMLHttpRequest(), blob;
  3149. xhr.open("GET", url, true);
  3150. xhr.responseType = "blob";
  3151. xhr.addEventListener("load", function () {
  3152. if (xhr.status === 200) {
  3153. // Blob as response (XHR2)
  3154. blob = xhr.response;
  3155. var transaction = _this.db.transaction(["textures"], "readwrite");
  3156. // the transaction could abort because of a QuotaExceededError error
  3157. transaction.onabort = function (event) {
  3158. try {
  3159. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3160. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3161. this.hasReachedQuota = true;
  3162. }
  3163. }
  3164. catch (ex) { }
  3165. generateBlobUrl();
  3166. };
  3167. transaction.oncomplete = function (event) {
  3168. generateBlobUrl();
  3169. };
  3170. var newTexture = { textureUrl: url, data: blob };
  3171. try {
  3172. // Put the blob into the dabase
  3173. var addRequest = transaction.objectStore("textures").put(newTexture);
  3174. addRequest.onsuccess = function (event) {
  3175. };
  3176. addRequest.onerror = function (event) {
  3177. generateBlobUrl();
  3178. };
  3179. }
  3180. catch (ex) {
  3181. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3182. if (ex.code === 25) {
  3183. Database.IsUASupportingBlobStorage = false;
  3184. }
  3185. image.src = url;
  3186. }
  3187. }
  3188. else {
  3189. image.src = url;
  3190. }
  3191. }, false);
  3192. xhr.addEventListener("error", function (event) {
  3193. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3194. image.src = url;
  3195. }, false);
  3196. xhr.send();
  3197. }
  3198. else {
  3199. image.src = url;
  3200. }
  3201. }
  3202. else {
  3203. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3204. image.src = url;
  3205. }
  3206. };
  3207. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3208. var _this = this;
  3209. var updateVersion = function (event) {
  3210. // the version is not yet in the DB or we need to update it
  3211. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3212. };
  3213. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3214. };
  3215. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3216. var _this = this;
  3217. if (this.isSupported) {
  3218. var version;
  3219. try {
  3220. var transaction = this.db.transaction(["versions"]);
  3221. transaction.oncomplete = function (event) {
  3222. if (version) {
  3223. // If the version in the JSON file is > than the version in DB
  3224. if (_this.manifestVersionFound > version.data) {
  3225. _this.mustUpdateRessources = true;
  3226. updateInDBCallback();
  3227. }
  3228. else {
  3229. callback(version.data);
  3230. }
  3231. }
  3232. else {
  3233. _this.mustUpdateRessources = true;
  3234. updateInDBCallback();
  3235. }
  3236. };
  3237. transaction.onabort = function (event) {
  3238. callback(-1);
  3239. };
  3240. var getRequest = transaction.objectStore("versions").get(url);
  3241. getRequest.onsuccess = function (event) {
  3242. version = (event.target).result;
  3243. };
  3244. getRequest.onerror = function (event) {
  3245. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3246. callback(-1);
  3247. };
  3248. }
  3249. catch (ex) {
  3250. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3251. callback(-1);
  3252. }
  3253. }
  3254. else {
  3255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3256. callback(-1);
  3257. }
  3258. };
  3259. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3260. var _this = this;
  3261. if (this.isSupported && !this.hasReachedQuota) {
  3262. try {
  3263. // Open a transaction to the database
  3264. var transaction = this.db.transaction(["versions"], "readwrite");
  3265. // the transaction could abort because of a QuotaExceededError error
  3266. transaction.onabort = function (event) {
  3267. try {
  3268. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3269. _this.hasReachedQuota = true;
  3270. }
  3271. }
  3272. catch (ex) { }
  3273. callback(-1);
  3274. };
  3275. transaction.oncomplete = function (event) {
  3276. callback(_this.manifestVersionFound);
  3277. };
  3278. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3279. // Put the scene into the database
  3280. var addRequest = transaction.objectStore("versions").put(newVersion);
  3281. addRequest.onsuccess = function (event) {
  3282. };
  3283. addRequest.onerror = function (event) {
  3284. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3285. };
  3286. }
  3287. catch (ex) {
  3288. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3289. callback(-1);
  3290. }
  3291. }
  3292. else {
  3293. callback(-1);
  3294. }
  3295. };
  3296. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3297. var _this = this;
  3298. var completeUrl = Database.ReturnFullUrlLocation(url);
  3299. var saveAndLoadFile = function (event) {
  3300. // the scene is not yet in the DB, let's try to save it
  3301. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3302. };
  3303. this._checkVersionFromDB(completeUrl, function (version) {
  3304. if (version !== -1) {
  3305. if (!_this.mustUpdateRessources) {
  3306. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3307. }
  3308. else {
  3309. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3310. }
  3311. }
  3312. else {
  3313. errorCallback();
  3314. }
  3315. });
  3316. };
  3317. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3318. if (this.isSupported) {
  3319. var targetStore;
  3320. if (url.indexOf(".babylon") !== -1) {
  3321. targetStore = "scenes";
  3322. }
  3323. else {
  3324. targetStore = "textures";
  3325. }
  3326. var file;
  3327. var transaction = this.db.transaction([targetStore]);
  3328. transaction.oncomplete = function (event) {
  3329. if (file) {
  3330. callback(file.data);
  3331. }
  3332. else {
  3333. notInDBCallback();
  3334. }
  3335. };
  3336. transaction.onabort = function (event) {
  3337. notInDBCallback();
  3338. };
  3339. var getRequest = transaction.objectStore(targetStore).get(url);
  3340. getRequest.onsuccess = function (event) {
  3341. file = (event.target).result;
  3342. };
  3343. getRequest.onerror = function (event) {
  3344. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3345. notInDBCallback();
  3346. };
  3347. }
  3348. else {
  3349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3350. callback();
  3351. }
  3352. };
  3353. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3354. var _this = this;
  3355. if (this.isSupported) {
  3356. var targetStore;
  3357. if (url.indexOf(".babylon") !== -1) {
  3358. targetStore = "scenes";
  3359. }
  3360. else {
  3361. targetStore = "textures";
  3362. }
  3363. // Create XHR
  3364. var xhr = new XMLHttpRequest(), fileData;
  3365. xhr.open("GET", url, true);
  3366. if (useArrayBuffer) {
  3367. xhr.responseType = "arraybuffer";
  3368. }
  3369. xhr.onprogress = progressCallback;
  3370. xhr.addEventListener("load", function () {
  3371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3372. // Blob as response (XHR2)
  3373. //fileData = xhr.responseText;
  3374. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3375. if (!_this.hasReachedQuota) {
  3376. // Open a transaction to the database
  3377. var transaction = _this.db.transaction([targetStore], "readwrite");
  3378. // the transaction could abort because of a QuotaExceededError error
  3379. transaction.onabort = function (event) {
  3380. try {
  3381. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3382. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3383. this.hasReachedQuota = true;
  3384. }
  3385. }
  3386. catch (ex) { }
  3387. callback(fileData);
  3388. };
  3389. transaction.oncomplete = function (event) {
  3390. callback(fileData);
  3391. };
  3392. var newFile;
  3393. if (targetStore === "scenes") {
  3394. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3395. }
  3396. else {
  3397. newFile = { textureUrl: url, data: fileData };
  3398. }
  3399. try {
  3400. // Put the scene into the database
  3401. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3402. addRequest.onsuccess = function (event) {
  3403. };
  3404. addRequest.onerror = function (event) {
  3405. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3406. };
  3407. }
  3408. catch (ex) {
  3409. callback(fileData);
  3410. }
  3411. }
  3412. else {
  3413. callback(fileData);
  3414. }
  3415. }
  3416. else {
  3417. callback();
  3418. }
  3419. }, false);
  3420. xhr.addEventListener("error", function (event) {
  3421. BABYLON.Tools.Error("error on XHR request.");
  3422. callback();
  3423. }, false);
  3424. xhr.send();
  3425. }
  3426. else {
  3427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3428. callback();
  3429. }
  3430. };
  3431. Database.IsUASupportingBlobStorage = true;
  3432. Database.IDBStorageEnabled = true;
  3433. Database.parseURL = function (url) {
  3434. var a = document.createElement('a');
  3435. a.href = url;
  3436. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3437. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3438. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3439. return absLocation;
  3440. };
  3441. Database.ReturnFullUrlLocation = function (url) {
  3442. if (url.indexOf("http:/") === -1) {
  3443. return (Database.parseURL(window.location.href) + url);
  3444. }
  3445. else {
  3446. return url;
  3447. }
  3448. };
  3449. return Database;
  3450. })();
  3451. BABYLON.Database = Database;
  3452. })(BABYLON || (BABYLON = {}));
  3453. var BABYLON;
  3454. (function (BABYLON) {
  3455. var Internals;
  3456. (function (Internals) {
  3457. /*
  3458. * Based on jsTGALoader - Javascript loader for TGA file
  3459. * By Vincent Thibault
  3460. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3461. */
  3462. var TGATools = (function () {
  3463. function TGATools() {
  3464. }
  3465. TGATools.GetTGAHeader = function (data) {
  3466. var offset = 0;
  3467. var header = {
  3468. id_length: data[offset++],
  3469. colormap_type: data[offset++],
  3470. image_type: data[offset++],
  3471. colormap_index: data[offset++] | data[offset++] << 8,
  3472. colormap_length: data[offset++] | data[offset++] << 8,
  3473. colormap_size: data[offset++],
  3474. origin: [
  3475. data[offset++] | data[offset++] << 8,
  3476. data[offset++] | data[offset++] << 8
  3477. ],
  3478. width: data[offset++] | data[offset++] << 8,
  3479. height: data[offset++] | data[offset++] << 8,
  3480. pixel_size: data[offset++],
  3481. flags: data[offset++]
  3482. };
  3483. return header;
  3484. };
  3485. TGATools.UploadContent = function (gl, data) {
  3486. // Not enough data to contain header ?
  3487. if (data.length < 19) {
  3488. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3489. return;
  3490. }
  3491. // Read Header
  3492. var offset = 18;
  3493. var header = TGATools.GetTGAHeader(data);
  3494. // Assume it's a valid Targa file.
  3495. if (header.id_length + offset > data.length) {
  3496. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3497. return;
  3498. }
  3499. // Skip not needed data
  3500. offset += header.id_length;
  3501. var use_rle = false;
  3502. var use_pal = false;
  3503. var use_rgb = false;
  3504. var use_grey = false;
  3505. // Get some informations.
  3506. switch (header.image_type) {
  3507. case TGATools._TYPE_RLE_INDEXED:
  3508. use_rle = true;
  3509. case TGATools._TYPE_INDEXED:
  3510. use_pal = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_RGB:
  3513. use_rle = true;
  3514. case TGATools._TYPE_RGB:
  3515. use_rgb = true;
  3516. break;
  3517. case TGATools._TYPE_RLE_GREY:
  3518. use_rle = true;
  3519. case TGATools._TYPE_GREY:
  3520. use_grey = true;
  3521. break;
  3522. }
  3523. var pixel_data;
  3524. var numAlphaBits = header.flags & 0xf;
  3525. var pixel_size = header.pixel_size >> 3;
  3526. var pixel_total = header.width * header.height * pixel_size;
  3527. // Read palettes
  3528. var palettes;
  3529. if (use_pal) {
  3530. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3531. }
  3532. // Read LRE
  3533. if (use_rle) {
  3534. pixel_data = new Uint8Array(pixel_total);
  3535. var c, count, i;
  3536. var localOffset = 0;
  3537. var pixels = new Uint8Array(pixel_size);
  3538. while (offset < pixel_total && localOffset < pixel_total) {
  3539. c = data[offset++];
  3540. count = (c & 0x7f) + 1;
  3541. // RLE pixels
  3542. if (c & 0x80) {
  3543. // Bind pixel tmp array
  3544. for (i = 0; i < pixel_size; ++i) {
  3545. pixels[i] = data[offset++];
  3546. }
  3547. // Copy pixel array
  3548. for (i = 0; i < count; ++i) {
  3549. pixel_data.set(pixels, localOffset + i * pixel_size);
  3550. }
  3551. localOffset += pixel_size * count;
  3552. }
  3553. else {
  3554. count *= pixel_size;
  3555. for (i = 0; i < count; ++i) {
  3556. pixel_data[localOffset + i] = data[offset++];
  3557. }
  3558. localOffset += count;
  3559. }
  3560. }
  3561. }
  3562. else {
  3563. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3564. }
  3565. // Load to texture
  3566. var x_start, y_start, x_step, y_step, y_end, x_end;
  3567. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3568. default:
  3569. case TGATools._ORIGIN_UL:
  3570. x_start = 0;
  3571. x_step = 1;
  3572. x_end = header.width;
  3573. y_start = 0;
  3574. y_step = 1;
  3575. y_end = header.height;
  3576. break;
  3577. case TGATools._ORIGIN_BL:
  3578. x_start = 0;
  3579. x_step = 1;
  3580. x_end = header.width;
  3581. y_start = header.height - 1;
  3582. y_step = -1;
  3583. y_end = -1;
  3584. break;
  3585. case TGATools._ORIGIN_UR:
  3586. x_start = header.width - 1;
  3587. x_step = -1;
  3588. x_end = -1;
  3589. y_start = 0;
  3590. y_step = 1;
  3591. y_end = header.height;
  3592. break;
  3593. case TGATools._ORIGIN_BR:
  3594. x_start = header.width - 1;
  3595. x_step = -1;
  3596. x_end = -1;
  3597. y_start = header.height - 1;
  3598. y_step = -1;
  3599. y_end = -1;
  3600. break;
  3601. }
  3602. // Load the specify method
  3603. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3604. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3605. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3606. };
  3607. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3608. var image = pixel_data, colormap = palettes;
  3609. var width = header.width, height = header.height;
  3610. var color, i = 0, x, y;
  3611. var imageData = new Uint8Array(width * height * 4);
  3612. for (y = y_start; y !== y_end; y += y_step) {
  3613. for (x = x_start; x !== x_end; x += x_step, i++) {
  3614. color = image[i];
  3615. imageData[(x + width * y) * 4 + 3] = 255;
  3616. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3617. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3618. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3619. }
  3620. }
  3621. return imageData;
  3622. };
  3623. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3624. var image = pixel_data;
  3625. var width = header.width, height = header.height;
  3626. var color, i = 0, x, y;
  3627. var imageData = new Uint8Array(width * height * 4);
  3628. for (y = y_start; y !== y_end; y += y_step) {
  3629. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3630. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3631. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3632. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3633. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3634. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3635. }
  3636. }
  3637. return imageData;
  3638. };
  3639. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3640. var image = pixel_data;
  3641. var width = header.width, height = header.height;
  3642. var i = 0, x, y;
  3643. var imageData = new Uint8Array(width * height * 4);
  3644. for (y = y_start; y !== y_end; y += y_step) {
  3645. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3646. imageData[(x + width * y) * 4 + 3] = 255;
  3647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3650. }
  3651. }
  3652. return imageData;
  3653. };
  3654. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3655. var image = pixel_data;
  3656. var width = header.width, height = header.height;
  3657. var i = 0, x, y;
  3658. var imageData = new Uint8Array(width * height * 4);
  3659. for (y = y_start; y !== y_end; y += y_step) {
  3660. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3662. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3663. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3664. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3665. }
  3666. }
  3667. return imageData;
  3668. };
  3669. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3670. var image = pixel_data;
  3671. var width = header.width, height = header.height;
  3672. var color, i = 0, x, y;
  3673. var imageData = new Uint8Array(width * height * 4);
  3674. for (y = y_start; y !== y_end; y += y_step) {
  3675. for (x = x_start; x !== x_end; x += x_step, i++) {
  3676. color = image[i];
  3677. imageData[(x + width * y) * 4 + 0] = color;
  3678. imageData[(x + width * y) * 4 + 1] = color;
  3679. imageData[(x + width * y) * 4 + 2] = color;
  3680. imageData[(x + width * y) * 4 + 3] = 255;
  3681. }
  3682. }
  3683. return imageData;
  3684. };
  3685. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3686. var image = pixel_data;
  3687. var width = header.width, height = header.height;
  3688. var i = 0, x, y;
  3689. var imageData = new Uint8Array(width * height * 4);
  3690. for (y = y_start; y !== y_end; y += y_step) {
  3691. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3692. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3693. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3694. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3695. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3696. }
  3697. }
  3698. return imageData;
  3699. };
  3700. TGATools._TYPE_NO_DATA = 0;
  3701. TGATools._TYPE_INDEXED = 1;
  3702. TGATools._TYPE_RGB = 2;
  3703. TGATools._TYPE_GREY = 3;
  3704. TGATools._TYPE_RLE_INDEXED = 9;
  3705. TGATools._TYPE_RLE_RGB = 10;
  3706. TGATools._TYPE_RLE_GREY = 11;
  3707. TGATools._ORIGIN_MASK = 0x30;
  3708. TGATools._ORIGIN_SHIFT = 0x04;
  3709. TGATools._ORIGIN_BL = 0x00;
  3710. TGATools._ORIGIN_BR = 0x01;
  3711. TGATools._ORIGIN_UL = 0x02;
  3712. TGATools._ORIGIN_UR = 0x03;
  3713. return TGATools;
  3714. })();
  3715. Internals.TGATools = TGATools;
  3716. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3717. })(BABYLON || (BABYLON = {}));
  3718. var BABYLON;
  3719. (function (BABYLON) {
  3720. var SmartArray = (function () {
  3721. function SmartArray(capacity) {
  3722. this.length = 0;
  3723. this._duplicateId = 0;
  3724. this.data = new Array(capacity);
  3725. this._id = SmartArray._GlobalId++;
  3726. }
  3727. SmartArray.prototype.push = function (value) {
  3728. this.data[this.length++] = value;
  3729. if (this.length > this.data.length) {
  3730. this.data.length *= 2;
  3731. }
  3732. if (!value.__smartArrayFlags) {
  3733. value.__smartArrayFlags = {};
  3734. }
  3735. value.__smartArrayFlags[this._id] = this._duplicateId;
  3736. };
  3737. SmartArray.prototype.pushNoDuplicate = function (value) {
  3738. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3739. return;
  3740. }
  3741. this.push(value);
  3742. };
  3743. SmartArray.prototype.sort = function (compareFn) {
  3744. this.data.sort(compareFn);
  3745. };
  3746. SmartArray.prototype.reset = function () {
  3747. this.length = 0;
  3748. this._duplicateId++;
  3749. };
  3750. SmartArray.prototype.concat = function (array) {
  3751. if (array.length === 0) {
  3752. return;
  3753. }
  3754. if (this.length + array.length > this.data.length) {
  3755. this.data.length = (this.length + array.length) * 2;
  3756. }
  3757. for (var index = 0; index < array.length; index++) {
  3758. this.data[this.length++] = (array.data || array)[index];
  3759. }
  3760. };
  3761. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3762. if (array.length === 0) {
  3763. return;
  3764. }
  3765. if (this.length + array.length > this.data.length) {
  3766. this.data.length = (this.length + array.length) * 2;
  3767. }
  3768. for (var index = 0; index < array.length; index++) {
  3769. var item = (array.data || array)[index];
  3770. this.pushNoDuplicate(item);
  3771. }
  3772. };
  3773. SmartArray.prototype.indexOf = function (value) {
  3774. var position = this.data.indexOf(value);
  3775. if (position >= this.length) {
  3776. return -1;
  3777. }
  3778. return position;
  3779. };
  3780. // Statics
  3781. SmartArray._GlobalId = 0;
  3782. return SmartArray;
  3783. })();
  3784. BABYLON.SmartArray = SmartArray;
  3785. })(BABYLON || (BABYLON = {}));
  3786. var BABYLON;
  3787. (function (BABYLON) {
  3788. var SmartCollection = (function () {
  3789. function SmartCollection(capacity) {
  3790. if (capacity === void 0) { capacity = 10; }
  3791. this.count = 0;
  3792. this._initialCapacity = capacity;
  3793. this.items = {};
  3794. this._keys = new Array(this._initialCapacity);
  3795. }
  3796. SmartCollection.prototype.add = function (key, item) {
  3797. if (this.items[key] != undefined) {
  3798. return -1;
  3799. }
  3800. this.items[key] = item;
  3801. //literal keys are always strings, but we keep source type of key in _keys array
  3802. this._keys[this.count++] = key;
  3803. if (this.count > this._keys.length) {
  3804. this._keys.length *= 2;
  3805. }
  3806. return this.count;
  3807. };
  3808. SmartCollection.prototype.remove = function (key) {
  3809. if (this.items[key] == undefined) {
  3810. return -1;
  3811. }
  3812. return this.removeItemOfIndex(this.indexOf(key));
  3813. };
  3814. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3815. if (index < this.count && index > -1) {
  3816. delete this.items[this._keys[index]];
  3817. //here, shifting by hand is better optimised than .splice
  3818. while (index < this.count) {
  3819. this._keys[index] = this._keys[index + 1];
  3820. index++;
  3821. }
  3822. }
  3823. else {
  3824. return -1;
  3825. }
  3826. return --this.count;
  3827. };
  3828. SmartCollection.prototype.indexOf = function (key) {
  3829. for (var i = 0; i !== this.count; i++) {
  3830. if (this._keys[i] === key) {
  3831. return i;
  3832. }
  3833. }
  3834. return -1;
  3835. };
  3836. SmartCollection.prototype.item = function (key) {
  3837. return this.items[key];
  3838. };
  3839. SmartCollection.prototype.getAllKeys = function () {
  3840. if (this.count > 0) {
  3841. var keys = new Array(this.count);
  3842. for (var i = 0; i < this.count; i++) {
  3843. keys[i] = this._keys[i];
  3844. }
  3845. return keys;
  3846. }
  3847. else {
  3848. return undefined;
  3849. }
  3850. };
  3851. SmartCollection.prototype.getKeyByIndex = function (index) {
  3852. if (index < this.count && index > -1) {
  3853. return this._keys[index];
  3854. }
  3855. else {
  3856. return undefined;
  3857. }
  3858. };
  3859. SmartCollection.prototype.getItemByIndex = function (index) {
  3860. if (index < this.count && index > -1) {
  3861. return this.items[this._keys[index]];
  3862. }
  3863. else {
  3864. return undefined;
  3865. }
  3866. };
  3867. SmartCollection.prototype.empty = function () {
  3868. if (this.count > 0) {
  3869. this.count = 0;
  3870. this.items = {};
  3871. this._keys = new Array(this._initialCapacity);
  3872. }
  3873. };
  3874. SmartCollection.prototype.forEach = function (block) {
  3875. var key;
  3876. for (key in this.items) {
  3877. if (this.items.hasOwnProperty(key)) {
  3878. block(this.items[key]);
  3879. }
  3880. }
  3881. };
  3882. return SmartCollection;
  3883. })();
  3884. BABYLON.SmartCollection = SmartCollection;
  3885. })(BABYLON || (BABYLON = {}));
  3886. var BABYLON;
  3887. (function (BABYLON) {
  3888. // Screenshots
  3889. var screenshotCanvas;
  3890. var cloneValue = function (source, destinationObject) {
  3891. if (!source)
  3892. return null;
  3893. if (source instanceof BABYLON.Mesh) {
  3894. return null;
  3895. }
  3896. if (source instanceof BABYLON.SubMesh) {
  3897. return source.clone(destinationObject);
  3898. }
  3899. else if (source.clone) {
  3900. return source.clone();
  3901. }
  3902. return null;
  3903. };
  3904. var Tools = (function () {
  3905. function Tools() {
  3906. }
  3907. Tools.Instantiate = function (className) {
  3908. var arr = className.split(".");
  3909. var fn = (window || this);
  3910. for (var i = 0, len = arr.length; i < len; i++) {
  3911. fn = fn[arr[i]];
  3912. }
  3913. if (typeof fn !== "function") {
  3914. return null;
  3915. }
  3916. return fn;
  3917. };
  3918. Tools.GetConstructorName = function (obj) {
  3919. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3920. var cname = str.match(/function\s(\w*)/)[1];
  3921. var aliases = ["", "anonymous", "Anonymous"];
  3922. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3923. };
  3924. Tools.ToHex = function (i) {
  3925. var str = i.toString(16);
  3926. if (i <= 15) {
  3927. return ("0" + str).toUpperCase();
  3928. }
  3929. return str.toUpperCase();
  3930. };
  3931. Tools.SetImmediate = function (action) {
  3932. if (window.setImmediate) {
  3933. window.setImmediate(action);
  3934. }
  3935. else {
  3936. setTimeout(action, 1);
  3937. }
  3938. };
  3939. Tools.IsExponentOfTwo = function (value) {
  3940. var count = 1;
  3941. do {
  3942. count *= 2;
  3943. } while (count < value);
  3944. return count === value;
  3945. };
  3946. Tools.GetExponentOfTwo = function (value, max) {
  3947. var count = 1;
  3948. do {
  3949. count *= 2;
  3950. } while (count < value);
  3951. if (count > max)
  3952. count = max;
  3953. return count;
  3954. };
  3955. Tools.GetFilename = function (path) {
  3956. var index = path.lastIndexOf("/");
  3957. if (index < 0)
  3958. return path;
  3959. return path.substring(index + 1);
  3960. };
  3961. Tools.GetDOMTextContent = function (element) {
  3962. var result = "";
  3963. var child = element.firstChild;
  3964. while (child) {
  3965. if (child.nodeType === 3) {
  3966. result += child.textContent;
  3967. }
  3968. child = child.nextSibling;
  3969. }
  3970. return result;
  3971. };
  3972. Tools.ToDegrees = function (angle) {
  3973. return angle * 180 / Math.PI;
  3974. };
  3975. Tools.ToRadians = function (angle) {
  3976. return angle * Math.PI / 180;
  3977. };
  3978. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3979. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3980. var output = "";
  3981. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3982. var i = 0;
  3983. var bytes = new Uint8Array(buffer);
  3984. while (i < bytes.length) {
  3985. chr1 = bytes[i++];
  3986. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3987. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3988. enc1 = chr1 >> 2;
  3989. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3990. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3991. enc4 = chr3 & 63;
  3992. if (isNaN(chr2)) {
  3993. enc3 = enc4 = 64;
  3994. }
  3995. else if (isNaN(chr3)) {
  3996. enc4 = 64;
  3997. }
  3998. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3999. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4000. }
  4001. return "data:image/png;base64," + output;
  4002. };
  4003. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4004. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4005. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4006. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4007. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4008. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4009. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4010. }
  4011. return {
  4012. minimum: minimum,
  4013. maximum: maximum
  4014. };
  4015. };
  4016. Tools.ExtractMinAndMax = function (positions, start, count) {
  4017. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4018. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4019. for (var index = start; index < start + count; index++) {
  4020. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4021. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4022. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4023. }
  4024. return {
  4025. minimum: minimum,
  4026. maximum: maximum
  4027. };
  4028. };
  4029. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4030. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4031. return undefined;
  4032. return Array.isArray(obj) ? obj : [obj];
  4033. };
  4034. // Misc.
  4035. Tools.GetPointerPrefix = function () {
  4036. var eventPrefix = "pointer";
  4037. // Check if pointer events are supported
  4038. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4039. eventPrefix = "mouse";
  4040. }
  4041. return eventPrefix;
  4042. };
  4043. Tools.QueueNewFrame = function (func) {
  4044. if (window.requestAnimationFrame)
  4045. window.requestAnimationFrame(func);
  4046. else if (window.msRequestAnimationFrame)
  4047. window.msRequestAnimationFrame(func);
  4048. else if (window.webkitRequestAnimationFrame)
  4049. window.webkitRequestAnimationFrame(func);
  4050. else if (window.mozRequestAnimationFrame)
  4051. window.mozRequestAnimationFrame(func);
  4052. else if (window.oRequestAnimationFrame)
  4053. window.oRequestAnimationFrame(func);
  4054. else {
  4055. window.setTimeout(func, 16);
  4056. }
  4057. };
  4058. Tools.RequestFullscreen = function (element) {
  4059. if (element.requestFullscreen)
  4060. element.requestFullscreen();
  4061. else if (element.msRequestFullscreen)
  4062. element.msRequestFullscreen();
  4063. else if (element.webkitRequestFullscreen)
  4064. element.webkitRequestFullscreen();
  4065. else if (element.mozRequestFullScreen)
  4066. element.mozRequestFullScreen();
  4067. };
  4068. Tools.ExitFullscreen = function () {
  4069. if (document.exitFullscreen) {
  4070. document.exitFullscreen();
  4071. }
  4072. else if (document.mozCancelFullScreen) {
  4073. document.mozCancelFullScreen();
  4074. }
  4075. else if (document.webkitCancelFullScreen) {
  4076. document.webkitCancelFullScreen();
  4077. }
  4078. else if (document.msCancelFullScreen) {
  4079. document.msCancelFullScreen();
  4080. }
  4081. };
  4082. // External files
  4083. Tools.CleanUrl = function (url) {
  4084. url = url.replace(/#/mg, "%23");
  4085. return url;
  4086. };
  4087. Tools.LoadImage = function (url, onload, onerror, database) {
  4088. if (url instanceof ArrayBuffer) {
  4089. url = Tools.EncodeArrayBufferTobase64(url);
  4090. }
  4091. url = Tools.CleanUrl(url);
  4092. var img = new Image();
  4093. if (url.substr(0, 5) !== "data:") {
  4094. if (Tools.CorsBehavior) {
  4095. switch (typeof (Tools.CorsBehavior)) {
  4096. case "function":
  4097. var result = Tools.CorsBehavior(url);
  4098. if (result) {
  4099. img.crossOrigin = result;
  4100. }
  4101. break;
  4102. case "string":
  4103. default:
  4104. img.crossOrigin = Tools.CorsBehavior;
  4105. break;
  4106. }
  4107. }
  4108. }
  4109. img.onload = function () {
  4110. onload(img);
  4111. };
  4112. img.onerror = function (err) {
  4113. Tools.Error("Error while trying to load texture: " + url);
  4114. 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";
  4115. onload(img);
  4116. };
  4117. var noIndexedDB = function () {
  4118. img.src = url;
  4119. };
  4120. var loadFromIndexedDB = function () {
  4121. database.loadImageFromDB(url, img);
  4122. };
  4123. //ANY database to do!
  4124. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4125. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4126. }
  4127. else {
  4128. if (url.indexOf("file:") === -1) {
  4129. noIndexedDB();
  4130. }
  4131. else {
  4132. try {
  4133. var textureName = url.substring(5);
  4134. var blobURL;
  4135. try {
  4136. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4137. }
  4138. catch (ex) {
  4139. // Chrome doesn't support oneTimeOnly parameter
  4140. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4141. }
  4142. img.src = blobURL;
  4143. }
  4144. catch (e) {
  4145. img.src = null;
  4146. }
  4147. }
  4148. }
  4149. return img;
  4150. };
  4151. //ANY
  4152. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4153. url = Tools.CleanUrl(url);
  4154. var noIndexedDB = function () {
  4155. var request = new XMLHttpRequest();
  4156. var loadUrl = Tools.BaseUrl + url;
  4157. request.open('GET', loadUrl, true);
  4158. if (useArrayBuffer) {
  4159. request.responseType = "arraybuffer";
  4160. }
  4161. request.onprogress = progressCallBack;
  4162. request.onreadystatechange = function () {
  4163. if (request.readyState === 4) {
  4164. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4165. callback(!useArrayBuffer ? request.responseText : request.response);
  4166. }
  4167. else {
  4168. if (onError) {
  4169. onError();
  4170. }
  4171. else {
  4172. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4173. }
  4174. }
  4175. }
  4176. };
  4177. request.send(null);
  4178. };
  4179. var loadFromIndexedDB = function () {
  4180. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4181. };
  4182. if (url.indexOf("file:") !== -1) {
  4183. var fileName = url.substring(5);
  4184. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4185. }
  4186. else {
  4187. // Caching all files
  4188. if (database && database.enableSceneOffline) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. noIndexedDB();
  4193. }
  4194. }
  4195. };
  4196. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4197. var reader = new FileReader();
  4198. reader.onload = function (e) {
  4199. //target doesn't have result from ts 1.3
  4200. callback(e.target['result']);
  4201. };
  4202. reader.onprogress = progressCallback;
  4203. reader.readAsDataURL(fileToLoad);
  4204. };
  4205. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4206. var reader = new FileReader();
  4207. reader.onerror = function (e) {
  4208. Tools.Log("Error while reading file: " + fileToLoad.name);
  4209. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4210. };
  4211. reader.onload = function (e) {
  4212. //target doesn't have result from ts 1.3
  4213. callback(e.target['result']);
  4214. };
  4215. reader.onprogress = progressCallBack;
  4216. if (!useArrayBuffer) {
  4217. // Asynchronous read
  4218. reader.readAsText(fileToLoad);
  4219. }
  4220. else {
  4221. reader.readAsArrayBuffer(fileToLoad);
  4222. }
  4223. };
  4224. //returns a downloadable url to a file content.
  4225. Tools.FileAsURL = function (content) {
  4226. var fileBlob = new Blob([content]);
  4227. var url = window.URL || window.webkitURL;
  4228. var link = url.createObjectURL(fileBlob);
  4229. return link;
  4230. };
  4231. // Misc.
  4232. Tools.Clamp = function (value, min, max) {
  4233. if (min === void 0) { min = 0; }
  4234. if (max === void 0) { max = 1; }
  4235. return Math.min(max, Math.max(min, value));
  4236. };
  4237. // Returns -1 when value is a negative number and
  4238. // +1 when value is a positive number.
  4239. Tools.Sign = function (value) {
  4240. value = +value; // convert to a number
  4241. if (value === 0 || isNaN(value))
  4242. return value;
  4243. return value > 0 ? 1 : -1;
  4244. };
  4245. Tools.Format = function (value, decimals) {
  4246. if (decimals === void 0) { decimals = 2; }
  4247. return value.toFixed(decimals);
  4248. };
  4249. Tools.CheckExtends = function (v, min, max) {
  4250. if (v.x < min.x)
  4251. min.x = v.x;
  4252. if (v.y < min.y)
  4253. min.y = v.y;
  4254. if (v.z < min.z)
  4255. min.z = v.z;
  4256. if (v.x > max.x)
  4257. max.x = v.x;
  4258. if (v.y > max.y)
  4259. max.y = v.y;
  4260. if (v.z > max.z)
  4261. max.z = v.z;
  4262. };
  4263. Tools.WithinEpsilon = function (a, b, epsilon) {
  4264. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4265. var num = a - b;
  4266. return -epsilon <= num && num <= epsilon;
  4267. };
  4268. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4269. for (var prop in source) {
  4270. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4271. continue;
  4272. }
  4273. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4274. continue;
  4275. }
  4276. var sourceValue = source[prop];
  4277. var typeOfSourceValue = typeof sourceValue;
  4278. if (typeOfSourceValue === "function") {
  4279. continue;
  4280. }
  4281. if (typeOfSourceValue === "object") {
  4282. if (sourceValue instanceof Array) {
  4283. destination[prop] = [];
  4284. if (sourceValue.length > 0) {
  4285. if (typeof sourceValue[0] == "object") {
  4286. for (var index = 0; index < sourceValue.length; index++) {
  4287. var clonedValue = cloneValue(sourceValue[index], destination);
  4288. if (destination[prop].indexOf(clonedValue) === -1) {
  4289. destination[prop].push(clonedValue);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = sourceValue.slice(0);
  4295. }
  4296. }
  4297. }
  4298. else {
  4299. destination[prop] = cloneValue(sourceValue, destination);
  4300. }
  4301. }
  4302. else {
  4303. destination[prop] = sourceValue;
  4304. }
  4305. }
  4306. };
  4307. Tools.IsEmpty = function (obj) {
  4308. for (var i in obj) {
  4309. return false;
  4310. }
  4311. return true;
  4312. };
  4313. Tools.RegisterTopRootEvents = function (events) {
  4314. for (var index = 0; index < events.length; index++) {
  4315. var event = events[index];
  4316. window.addEventListener(event.name, event.handler, false);
  4317. try {
  4318. if (window.parent) {
  4319. window.parent.addEventListener(event.name, event.handler, false);
  4320. }
  4321. }
  4322. catch (e) {
  4323. }
  4324. }
  4325. };
  4326. Tools.UnregisterTopRootEvents = function (events) {
  4327. for (var index = 0; index < events.length; index++) {
  4328. var event = events[index];
  4329. window.removeEventListener(event.name, event.handler);
  4330. try {
  4331. if (window.parent) {
  4332. window.parent.removeEventListener(event.name, event.handler);
  4333. }
  4334. }
  4335. catch (e) {
  4336. }
  4337. }
  4338. };
  4339. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4340. // Read the contents of the framebuffer
  4341. var numberOfChannelsByLine = width * 4;
  4342. var halfHeight = height / 2;
  4343. //Reading datas from WebGL
  4344. var data = engine.readPixels(0, 0, width, height);
  4345. //To flip image on Y axis.
  4346. for (var i = 0; i < halfHeight; i++) {
  4347. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4348. var currentCell = j + i * numberOfChannelsByLine;
  4349. var targetLine = height - i - 1;
  4350. var targetCell = j + targetLine * numberOfChannelsByLine;
  4351. var temp = data[currentCell];
  4352. data[currentCell] = data[targetCell];
  4353. data[targetCell] = temp;
  4354. }
  4355. }
  4356. // Create a 2D canvas to store the result
  4357. if (!screenshotCanvas) {
  4358. screenshotCanvas = document.createElement('canvas');
  4359. }
  4360. screenshotCanvas.width = width;
  4361. screenshotCanvas.height = height;
  4362. var context = screenshotCanvas.getContext('2d');
  4363. // Copy the pixels to a 2D canvas
  4364. var imageData = context.createImageData(width, height);
  4365. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4366. var castData = imageData.data;
  4367. castData.set(data);
  4368. context.putImageData(imageData, 0, 0);
  4369. var base64Image = screenshotCanvas.toDataURL();
  4370. if (successCallback) {
  4371. successCallback(base64Image);
  4372. }
  4373. else {
  4374. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4375. if (("download" in document.createElement("a"))) {
  4376. var a = window.document.createElement("a");
  4377. a.href = base64Image;
  4378. var date = new Date();
  4379. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4380. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4381. window.document.body.appendChild(a);
  4382. a.addEventListener("click", function () {
  4383. a.parentElement.removeChild(a);
  4384. });
  4385. a.click();
  4386. }
  4387. else {
  4388. var newWindow = window.open("");
  4389. var img = newWindow.document.createElement("img");
  4390. img.src = base64Image;
  4391. newWindow.document.body.appendChild(img);
  4392. }
  4393. }
  4394. };
  4395. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4396. var width;
  4397. var height;
  4398. //If a precision value is specified
  4399. if (size.precision) {
  4400. width = Math.round(engine.getRenderWidth() * size.precision);
  4401. height = Math.round(width / engine.getAspectRatio(camera));
  4402. size = { width: width, height: height };
  4403. }
  4404. else if (size.width && size.height) {
  4405. width = size.width;
  4406. height = size.height;
  4407. }
  4408. else if (size.width && !size.height) {
  4409. width = size.width;
  4410. height = Math.round(width / engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (size.height && !size.width) {
  4414. height = size.height;
  4415. width = Math.round(height * engine.getAspectRatio(camera));
  4416. size = { width: width, height: height };
  4417. }
  4418. else if (!isNaN(size)) {
  4419. height = size;
  4420. width = size;
  4421. }
  4422. else {
  4423. Tools.Error("Invalid 'size' parameter !");
  4424. return;
  4425. }
  4426. var scene = camera.getScene();
  4427. var previousCamera = null;
  4428. if (scene.activeCamera !== camera) {
  4429. previousCamera = scene.activeCamera;
  4430. scene.activeCamera = camera;
  4431. }
  4432. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4433. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4434. texture.renderList = scene.meshes;
  4435. texture.onAfterRender = function () {
  4436. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4437. };
  4438. scene.incrementRenderId();
  4439. texture.render(true);
  4440. texture.dispose();
  4441. if (previousCamera) {
  4442. scene.activeCamera = previousCamera;
  4443. }
  4444. };
  4445. // XHR response validator for local file scenario
  4446. Tools.ValidateXHRData = function (xhr, dataType) {
  4447. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4448. if (dataType === void 0) { dataType = 7; }
  4449. try {
  4450. if (dataType & 1) {
  4451. if (xhr.responseText && xhr.responseText.length > 0) {
  4452. return true;
  4453. }
  4454. else if (dataType === 1) {
  4455. return false;
  4456. }
  4457. }
  4458. if (dataType & 2) {
  4459. // Check header width and height since there is no "TGA" magic number
  4460. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4461. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4462. return true;
  4463. }
  4464. else if (dataType === 2) {
  4465. return false;
  4466. }
  4467. }
  4468. if (dataType & 4) {
  4469. // Check for the "DDS" magic number
  4470. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4471. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4472. return true;
  4473. }
  4474. else {
  4475. return false;
  4476. }
  4477. }
  4478. }
  4479. catch (e) {
  4480. }
  4481. return false;
  4482. };
  4483. Object.defineProperty(Tools, "NoneLogLevel", {
  4484. get: function () {
  4485. return Tools._NoneLogLevel;
  4486. },
  4487. enumerable: true,
  4488. configurable: true
  4489. });
  4490. Object.defineProperty(Tools, "MessageLogLevel", {
  4491. get: function () {
  4492. return Tools._MessageLogLevel;
  4493. },
  4494. enumerable: true,
  4495. configurable: true
  4496. });
  4497. Object.defineProperty(Tools, "WarningLogLevel", {
  4498. get: function () {
  4499. return Tools._WarningLogLevel;
  4500. },
  4501. enumerable: true,
  4502. configurable: true
  4503. });
  4504. Object.defineProperty(Tools, "ErrorLogLevel", {
  4505. get: function () {
  4506. return Tools._ErrorLogLevel;
  4507. },
  4508. enumerable: true,
  4509. configurable: true
  4510. });
  4511. Object.defineProperty(Tools, "AllLogLevel", {
  4512. get: function () {
  4513. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4514. },
  4515. enumerable: true,
  4516. configurable: true
  4517. });
  4518. Tools._AddLogEntry = function (entry) {
  4519. Tools._LogCache = entry + Tools._LogCache;
  4520. if (Tools.OnNewCacheEntry) {
  4521. Tools.OnNewCacheEntry(entry);
  4522. }
  4523. };
  4524. Tools._FormatMessage = function (message) {
  4525. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4526. var date = new Date();
  4527. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4528. };
  4529. Tools._LogDisabled = function (message) {
  4530. // nothing to do
  4531. };
  4532. Tools._LogEnabled = function (message) {
  4533. var formattedMessage = Tools._FormatMessage(message);
  4534. console.log("BJS - " + formattedMessage);
  4535. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4536. Tools._AddLogEntry(entry);
  4537. };
  4538. Tools._WarnDisabled = function (message) {
  4539. // nothing to do
  4540. };
  4541. Tools._WarnEnabled = function (message) {
  4542. var formattedMessage = Tools._FormatMessage(message);
  4543. console.warn("BJS - " + formattedMessage);
  4544. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4545. Tools._AddLogEntry(entry);
  4546. };
  4547. Tools._ErrorDisabled = function (message) {
  4548. // nothing to do
  4549. };
  4550. Tools._ErrorEnabled = function (message) {
  4551. Tools.errorsCount++;
  4552. var formattedMessage = Tools._FormatMessage(message);
  4553. console.error("BJS - " + formattedMessage);
  4554. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4555. Tools._AddLogEntry(entry);
  4556. };
  4557. Object.defineProperty(Tools, "LogCache", {
  4558. get: function () {
  4559. return Tools._LogCache;
  4560. },
  4561. enumerable: true,
  4562. configurable: true
  4563. });
  4564. Tools.ClearLogCache = function () {
  4565. Tools._LogCache = "";
  4566. Tools.errorsCount = 0;
  4567. };
  4568. Object.defineProperty(Tools, "LogLevels", {
  4569. set: function (level) {
  4570. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4571. Tools.Log = Tools._LogEnabled;
  4572. }
  4573. else {
  4574. Tools.Log = Tools._LogDisabled;
  4575. }
  4576. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4577. Tools.Warn = Tools._WarnEnabled;
  4578. }
  4579. else {
  4580. Tools.Warn = Tools._WarnDisabled;
  4581. }
  4582. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4583. Tools.Error = Tools._ErrorEnabled;
  4584. }
  4585. else {
  4586. Tools.Error = Tools._ErrorDisabled;
  4587. }
  4588. },
  4589. enumerable: true,
  4590. configurable: true
  4591. });
  4592. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4593. get: function () {
  4594. return Tools._PerformanceNoneLogLevel;
  4595. },
  4596. enumerable: true,
  4597. configurable: true
  4598. });
  4599. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4600. get: function () {
  4601. return Tools._PerformanceUserMarkLogLevel;
  4602. },
  4603. enumerable: true,
  4604. configurable: true
  4605. });
  4606. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4607. get: function () {
  4608. return Tools._PerformanceConsoleLogLevel;
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4614. set: function (level) {
  4615. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4616. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4617. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4618. return;
  4619. }
  4620. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4621. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4622. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4623. return;
  4624. }
  4625. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4626. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4632. };
  4633. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4634. };
  4635. Tools._StartUserMark = function (counterName, condition) {
  4636. if (condition === void 0) { condition = true; }
  4637. if (!condition || !Tools._performance.mark) {
  4638. return;
  4639. }
  4640. Tools._performance.mark(counterName + "-Begin");
  4641. };
  4642. Tools._EndUserMark = function (counterName, condition) {
  4643. if (condition === void 0) { condition = true; }
  4644. if (!condition || !Tools._performance.mark) {
  4645. return;
  4646. }
  4647. Tools._performance.mark(counterName + "-End");
  4648. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4649. };
  4650. Tools._StartPerformanceConsole = function (counterName, condition) {
  4651. if (condition === void 0) { condition = true; }
  4652. if (!condition) {
  4653. return;
  4654. }
  4655. Tools._StartUserMark(counterName, condition);
  4656. if (console.time) {
  4657. console.time(counterName);
  4658. }
  4659. };
  4660. Tools._EndPerformanceConsole = function (counterName, condition) {
  4661. if (condition === void 0) { condition = true; }
  4662. if (!condition) {
  4663. return;
  4664. }
  4665. Tools._EndUserMark(counterName, condition);
  4666. if (console.time) {
  4667. console.timeEnd(counterName);
  4668. }
  4669. };
  4670. Object.defineProperty(Tools, "Now", {
  4671. get: function () {
  4672. if (window.performance && window.performance.now) {
  4673. return window.performance.now();
  4674. }
  4675. return new Date().getTime();
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Tools.BaseUrl = "";
  4681. Tools.CorsBehavior = "anonymous";
  4682. // Logs
  4683. Tools._NoneLogLevel = 0;
  4684. Tools._MessageLogLevel = 1;
  4685. Tools._WarningLogLevel = 2;
  4686. Tools._ErrorLogLevel = 4;
  4687. Tools._LogCache = "";
  4688. Tools.errorsCount = 0;
  4689. Tools.Log = Tools._LogEnabled;
  4690. Tools.Warn = Tools._WarnEnabled;
  4691. Tools.Error = Tools._ErrorEnabled;
  4692. // Performances
  4693. Tools._PerformanceNoneLogLevel = 0;
  4694. Tools._PerformanceUserMarkLogLevel = 1;
  4695. Tools._PerformanceConsoleLogLevel = 2;
  4696. Tools._performance = window.performance;
  4697. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4698. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4699. return Tools;
  4700. })();
  4701. BABYLON.Tools = Tools;
  4702. /**
  4703. * An implementation of a loop for asynchronous functions.
  4704. */
  4705. var AsyncLoop = (function () {
  4706. /**
  4707. * Constroctor.
  4708. * @param iterations the number of iterations.
  4709. * @param _fn the function to run each iteration
  4710. * @param _successCallback the callback that will be called upon succesful execution
  4711. * @param offset starting offset.
  4712. */
  4713. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4714. if (offset === void 0) { offset = 0; }
  4715. this.iterations = iterations;
  4716. this._fn = _fn;
  4717. this._successCallback = _successCallback;
  4718. this.index = offset - 1;
  4719. this._done = false;
  4720. }
  4721. /**
  4722. * Execute the next iteration. Must be called after the last iteration was finished.
  4723. */
  4724. AsyncLoop.prototype.executeNext = function () {
  4725. if (!this._done) {
  4726. if (this.index + 1 < this.iterations) {
  4727. ++this.index;
  4728. this._fn(this);
  4729. }
  4730. else {
  4731. this.breakLoop();
  4732. }
  4733. }
  4734. };
  4735. /**
  4736. * Break the loop and run the success callback.
  4737. */
  4738. AsyncLoop.prototype.breakLoop = function () {
  4739. this._done = true;
  4740. this._successCallback();
  4741. };
  4742. /**
  4743. * Helper function
  4744. */
  4745. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4746. if (offset === void 0) { offset = 0; }
  4747. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4748. loop.executeNext();
  4749. return loop;
  4750. };
  4751. /**
  4752. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4753. * @param iterations total number of iterations
  4754. * @param syncedIterations number of synchronous iterations in each async iteration.
  4755. * @param fn the function to call each iteration.
  4756. * @param callback a success call back that will be called when iterating stops.
  4757. * @param breakFunction a break condition (optional)
  4758. * @param timeout timeout settings for the setTimeout function. default - 0.
  4759. * @constructor
  4760. */
  4761. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4762. if (timeout === void 0) { timeout = 0; }
  4763. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4764. if (breakFunction && breakFunction())
  4765. loop.breakLoop();
  4766. else {
  4767. setTimeout(function () {
  4768. for (var i = 0; i < syncedIterations; ++i) {
  4769. var iteration = (loop.index * syncedIterations) + i;
  4770. if (iteration >= iterations)
  4771. break;
  4772. fn(iteration);
  4773. if (breakFunction && breakFunction()) {
  4774. loop.breakLoop();
  4775. break;
  4776. }
  4777. }
  4778. loop.executeNext();
  4779. }, timeout);
  4780. }
  4781. }, callback);
  4782. };
  4783. return AsyncLoop;
  4784. })();
  4785. BABYLON.AsyncLoop = AsyncLoop;
  4786. })(BABYLON || (BABYLON = {}));
  4787. var BABYLON;
  4788. (function (BABYLON) {
  4789. var _DepthCullingState = (function () {
  4790. function _DepthCullingState() {
  4791. this._isDepthTestDirty = false;
  4792. this._isDepthMaskDirty = false;
  4793. this._isDepthFuncDirty = false;
  4794. this._isCullFaceDirty = false;
  4795. this._isCullDirty = false;
  4796. this._isZOffsetDirty = false;
  4797. }
  4798. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4799. get: function () {
  4800. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4801. },
  4802. enumerable: true,
  4803. configurable: true
  4804. });
  4805. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4806. get: function () {
  4807. return this._zOffset;
  4808. },
  4809. set: function (value) {
  4810. if (this._zOffset === value) {
  4811. return;
  4812. }
  4813. this._zOffset = value;
  4814. this._isZOffsetDirty = true;
  4815. },
  4816. enumerable: true,
  4817. configurable: true
  4818. });
  4819. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4820. get: function () {
  4821. return this._cullFace;
  4822. },
  4823. set: function (value) {
  4824. if (this._cullFace === value) {
  4825. return;
  4826. }
  4827. this._cullFace = value;
  4828. this._isCullFaceDirty = true;
  4829. },
  4830. enumerable: true,
  4831. configurable: true
  4832. });
  4833. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4834. get: function () {
  4835. return this._cull;
  4836. },
  4837. set: function (value) {
  4838. if (this._cull === value) {
  4839. return;
  4840. }
  4841. this._cull = value;
  4842. this._isCullDirty = true;
  4843. },
  4844. enumerable: true,
  4845. configurable: true
  4846. });
  4847. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4848. get: function () {
  4849. return this._depthFunc;
  4850. },
  4851. set: function (value) {
  4852. if (this._depthFunc === value) {
  4853. return;
  4854. }
  4855. this._depthFunc = value;
  4856. this._isDepthFuncDirty = true;
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4862. get: function () {
  4863. return this._depthMask;
  4864. },
  4865. set: function (value) {
  4866. if (this._depthMask === value) {
  4867. return;
  4868. }
  4869. this._depthMask = value;
  4870. this._isDepthMaskDirty = true;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4876. get: function () {
  4877. return this._depthTest;
  4878. },
  4879. set: function (value) {
  4880. if (this._depthTest === value) {
  4881. return;
  4882. }
  4883. this._depthTest = value;
  4884. this._isDepthTestDirty = true;
  4885. },
  4886. enumerable: true,
  4887. configurable: true
  4888. });
  4889. _DepthCullingState.prototype.reset = function () {
  4890. this._depthMask = true;
  4891. this._depthTest = true;
  4892. this._depthFunc = null;
  4893. this._cull = null;
  4894. this._cullFace = null;
  4895. this._zOffset = 0;
  4896. this._isDepthTestDirty = true;
  4897. this._isDepthMaskDirty = true;
  4898. this._isDepthFuncDirty = false;
  4899. this._isCullFaceDirty = false;
  4900. this._isCullDirty = false;
  4901. this._isZOffsetDirty = false;
  4902. };
  4903. _DepthCullingState.prototype.apply = function (gl) {
  4904. if (!this.isDirty) {
  4905. return;
  4906. }
  4907. // Cull
  4908. if (this._isCullDirty) {
  4909. if (this.cull) {
  4910. gl.enable(gl.CULL_FACE);
  4911. }
  4912. else {
  4913. gl.disable(gl.CULL_FACE);
  4914. }
  4915. this._isCullDirty = false;
  4916. }
  4917. // Cull face
  4918. if (this._isCullFaceDirty) {
  4919. gl.cullFace(this.cullFace);
  4920. this._isCullFaceDirty = false;
  4921. }
  4922. // Depth mask
  4923. if (this._isDepthMaskDirty) {
  4924. gl.depthMask(this.depthMask);
  4925. this._isDepthMaskDirty = false;
  4926. }
  4927. // Depth test
  4928. if (this._isDepthTestDirty) {
  4929. if (this.depthTest) {
  4930. gl.enable(gl.DEPTH_TEST);
  4931. }
  4932. else {
  4933. gl.disable(gl.DEPTH_TEST);
  4934. }
  4935. this._isDepthTestDirty = false;
  4936. }
  4937. // Depth func
  4938. if (this._isDepthFuncDirty) {
  4939. gl.depthFunc(this.depthFunc);
  4940. this._isDepthFuncDirty = false;
  4941. }
  4942. // zOffset
  4943. if (this._isZOffsetDirty) {
  4944. if (this.zOffset) {
  4945. gl.enable(gl.POLYGON_OFFSET_FILL);
  4946. gl.polygonOffset(this.zOffset, 0);
  4947. }
  4948. else {
  4949. gl.disable(gl.POLYGON_OFFSET_FILL);
  4950. }
  4951. this._isZOffsetDirty = false;
  4952. }
  4953. };
  4954. return _DepthCullingState;
  4955. })();
  4956. BABYLON._DepthCullingState = _DepthCullingState;
  4957. var _AlphaState = (function () {
  4958. function _AlphaState() {
  4959. this._isAlphaBlendDirty = false;
  4960. this._isBlendFunctionParametersDirty = false;
  4961. this._alphaBlend = false;
  4962. this._blendFunctionParameters = new Array(4);
  4963. }
  4964. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4965. get: function () {
  4966. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4967. },
  4968. enumerable: true,
  4969. configurable: true
  4970. });
  4971. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4972. get: function () {
  4973. return this._alphaBlend;
  4974. },
  4975. set: function (value) {
  4976. if (this._alphaBlend === value) {
  4977. return;
  4978. }
  4979. this._alphaBlend = value;
  4980. this._isAlphaBlendDirty = true;
  4981. },
  4982. enumerable: true,
  4983. configurable: true
  4984. });
  4985. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4986. if (this._blendFunctionParameters[0] === value0 &&
  4987. this._blendFunctionParameters[1] === value1 &&
  4988. this._blendFunctionParameters[2] === value2 &&
  4989. this._blendFunctionParameters[3] === value3) {
  4990. return;
  4991. }
  4992. this._blendFunctionParameters[0] = value0;
  4993. this._blendFunctionParameters[1] = value1;
  4994. this._blendFunctionParameters[2] = value2;
  4995. this._blendFunctionParameters[3] = value3;
  4996. this._isBlendFunctionParametersDirty = true;
  4997. };
  4998. _AlphaState.prototype.reset = function () {
  4999. this._alphaBlend = false;
  5000. this._blendFunctionParameters[0] = null;
  5001. this._blendFunctionParameters[1] = null;
  5002. this._blendFunctionParameters[2] = null;
  5003. this._blendFunctionParameters[3] = null;
  5004. this._isAlphaBlendDirty = true;
  5005. this._isBlendFunctionParametersDirty = false;
  5006. };
  5007. _AlphaState.prototype.apply = function (gl) {
  5008. if (!this.isDirty) {
  5009. return;
  5010. }
  5011. // Alpha blend
  5012. if (this._isAlphaBlendDirty) {
  5013. if (this._alphaBlend) {
  5014. gl.enable(gl.BLEND);
  5015. }
  5016. else {
  5017. gl.disable(gl.BLEND);
  5018. }
  5019. this._isAlphaBlendDirty = false;
  5020. }
  5021. // Alpha function
  5022. if (this._isBlendFunctionParametersDirty) {
  5023. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5024. this._isBlendFunctionParametersDirty = false;
  5025. }
  5026. };
  5027. return _AlphaState;
  5028. })();
  5029. BABYLON._AlphaState = _AlphaState;
  5030. var compileShader = function (gl, source, type, defines) {
  5031. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5032. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5033. gl.compileShader(shader);
  5034. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5035. throw new Error(gl.getShaderInfoLog(shader));
  5036. }
  5037. return shader;
  5038. };
  5039. var getWebGLTextureType = function (gl, type) {
  5040. var textureType = gl.UNSIGNED_BYTE;
  5041. if (type === Engine.TEXTURETYPE_FLOAT)
  5042. textureType = gl.FLOAT;
  5043. return textureType;
  5044. };
  5045. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5046. var magFilter = gl.NEAREST;
  5047. var minFilter = gl.NEAREST;
  5048. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5049. magFilter = gl.LINEAR;
  5050. if (generateMipMaps) {
  5051. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5052. }
  5053. else {
  5054. minFilter = gl.LINEAR;
  5055. }
  5056. }
  5057. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5058. magFilter = gl.LINEAR;
  5059. if (generateMipMaps) {
  5060. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5061. }
  5062. else {
  5063. minFilter = gl.LINEAR;
  5064. }
  5065. }
  5066. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5067. magFilter = gl.NEAREST;
  5068. if (generateMipMaps) {
  5069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5070. }
  5071. else {
  5072. minFilter = gl.NEAREST;
  5073. }
  5074. }
  5075. return {
  5076. min: minFilter,
  5077. mag: magFilter
  5078. };
  5079. };
  5080. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5082. var engine = scene.getEngine();
  5083. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5084. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5085. gl.bindTexture(gl.TEXTURE_2D, texture);
  5086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5087. texture._baseWidth = width;
  5088. texture._baseHeight = height;
  5089. texture._width = potWidth;
  5090. texture._height = potHeight;
  5091. texture.isReady = true;
  5092. processFunction(potWidth, potHeight);
  5093. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5096. if (!noMipmap && !isCompressed) {
  5097. gl.generateMipmap(gl.TEXTURE_2D);
  5098. }
  5099. gl.bindTexture(gl.TEXTURE_2D, null);
  5100. engine.resetTextureCache();
  5101. scene._removePendingData(texture);
  5102. };
  5103. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5104. var img;
  5105. var onload = function () {
  5106. loadedImages[index] = img;
  5107. loadedImages._internalCount++;
  5108. scene._removePendingData(img);
  5109. if (loadedImages._internalCount === 6) {
  5110. onfinish(loadedImages);
  5111. }
  5112. };
  5113. var onerror = function () {
  5114. scene._removePendingData(img);
  5115. };
  5116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5117. scene._addPendingData(img);
  5118. };
  5119. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5120. var loadedImages = [];
  5121. loadedImages._internalCount = 0;
  5122. for (var index = 0; index < 6; index++) {
  5123. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5124. }
  5125. };
  5126. var EngineCapabilities = (function () {
  5127. function EngineCapabilities() {
  5128. }
  5129. return EngineCapabilities;
  5130. })();
  5131. BABYLON.EngineCapabilities = EngineCapabilities;
  5132. /**
  5133. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5134. */
  5135. var Engine = (function () {
  5136. /**
  5137. * @constructor
  5138. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5139. * @param {boolean} [antialias] - enable antialias
  5140. * @param options - further options to be sent to the getContext function
  5141. */
  5142. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5143. var _this = this;
  5144. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5145. // Public members
  5146. this.isFullscreen = false;
  5147. this.isPointerLock = false;
  5148. this.cullBackFaces = true;
  5149. this.renderEvenInBackground = true;
  5150. // To enable/disable IDB support and avoid XHR on .manifest
  5151. this.enableOfflineSupport = true;
  5152. this.scenes = new Array();
  5153. this._windowIsBackground = false;
  5154. this._drawCalls = 0;
  5155. this._renderingQueueLaunched = false;
  5156. this._activeRenderLoops = [];
  5157. // FPS
  5158. this.fpsRange = 60;
  5159. this.previousFramesDuration = [];
  5160. this.fps = 60;
  5161. this.deltaTime = 0;
  5162. // States
  5163. this._depthCullingState = new _DepthCullingState();
  5164. this._alphaState = new _AlphaState();
  5165. this._alphaMode = Engine.ALPHA_DISABLE;
  5166. // Cache
  5167. this._loadedTexturesCache = new Array();
  5168. this._maxTextureChannels = 16;
  5169. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5170. this._compiledEffects = {};
  5171. this._uintIndicesCurrentlySet = false;
  5172. this._renderingCanvas = canvas;
  5173. options = options || {};
  5174. options.antialias = antialias;
  5175. if (options.preserveDrawingBuffer === undefined) {
  5176. options.preserveDrawingBuffer = false;
  5177. }
  5178. // GL
  5179. try {
  5180. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5181. }
  5182. catch (e) {
  5183. throw new Error("WebGL not supported");
  5184. }
  5185. if (!this._gl) {
  5186. throw new Error("WebGL not supported");
  5187. }
  5188. this._onBlur = function () {
  5189. _this._windowIsBackground = true;
  5190. };
  5191. this._onFocus = function () {
  5192. _this._windowIsBackground = false;
  5193. };
  5194. window.addEventListener("blur", this._onBlur);
  5195. window.addEventListener("focus", this._onFocus);
  5196. // Viewport
  5197. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5198. this.resize();
  5199. // Caps
  5200. this._caps = new EngineCapabilities();
  5201. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5202. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5203. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5204. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5205. // Infos
  5206. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5207. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5208. if (rendererInfo != null) {
  5209. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5210. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5211. }
  5212. if (!this._glVendor) {
  5213. this._glVendor = "Unknown vendor";
  5214. }
  5215. if (!this._glRenderer) {
  5216. this._glRenderer = "Unknown renderer";
  5217. }
  5218. // Extensions
  5219. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5220. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5221. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5222. 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');
  5223. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5224. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5225. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5226. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5227. this._caps.highPrecisionShaderSupported = true;
  5228. if (this._gl.getShaderPrecisionFormat) {
  5229. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5230. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5231. }
  5232. // Depth buffer
  5233. this.setDepthBuffer(true);
  5234. this.setDepthFunctionToLessOrEqual();
  5235. this.setDepthWrite(true);
  5236. // Fullscreen
  5237. this._onFullscreenChange = function () {
  5238. if (document.fullscreen !== undefined) {
  5239. _this.isFullscreen = document.fullscreen;
  5240. }
  5241. else if (document.mozFullScreen !== undefined) {
  5242. _this.isFullscreen = document.mozFullScreen;
  5243. }
  5244. else if (document.webkitIsFullScreen !== undefined) {
  5245. _this.isFullscreen = document.webkitIsFullScreen;
  5246. }
  5247. else if (document.msIsFullScreen !== undefined) {
  5248. _this.isFullscreen = document.msIsFullScreen;
  5249. }
  5250. // Pointer lock
  5251. if (_this.isFullscreen && _this._pointerLockRequested) {
  5252. canvas.requestPointerLock = canvas.requestPointerLock ||
  5253. canvas.msRequestPointerLock ||
  5254. canvas.mozRequestPointerLock ||
  5255. canvas.webkitRequestPointerLock;
  5256. if (canvas.requestPointerLock) {
  5257. canvas.requestPointerLock();
  5258. }
  5259. }
  5260. };
  5261. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5262. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5263. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5264. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5265. // Pointer lock
  5266. this._onPointerLockChange = function () {
  5267. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5268. document.webkitPointerLockElement === canvas ||
  5269. document.msPointerLockElement === canvas ||
  5270. document.pointerLockElement === canvas);
  5271. };
  5272. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5273. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5274. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5275. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5276. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5277. Engine.audioEngine = new BABYLON.AudioEngine();
  5278. }
  5279. //default loading screen
  5280. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5281. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5282. }
  5283. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5284. get: function () {
  5285. return Engine._ALPHA_DISABLE;
  5286. },
  5287. enumerable: true,
  5288. configurable: true
  5289. });
  5290. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5291. get: function () {
  5292. return Engine._ALPHA_ONEONE;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. Object.defineProperty(Engine, "ALPHA_ADD", {
  5298. get: function () {
  5299. return Engine._ALPHA_ADD;
  5300. },
  5301. enumerable: true,
  5302. configurable: true
  5303. });
  5304. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5305. get: function () {
  5306. return Engine._ALPHA_COMBINE;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5312. get: function () {
  5313. return Engine._ALPHA_SUBTRACT;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5319. get: function () {
  5320. return Engine._ALPHA_MULTIPLY;
  5321. },
  5322. enumerable: true,
  5323. configurable: true
  5324. });
  5325. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5326. get: function () {
  5327. return Engine._ALPHA_MAXIMIZED;
  5328. },
  5329. enumerable: true,
  5330. configurable: true
  5331. });
  5332. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5333. get: function () {
  5334. return Engine._DELAYLOADSTATE_NONE;
  5335. },
  5336. enumerable: true,
  5337. configurable: true
  5338. });
  5339. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5340. get: function () {
  5341. return Engine._DELAYLOADSTATE_LOADED;
  5342. },
  5343. enumerable: true,
  5344. configurable: true
  5345. });
  5346. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5347. get: function () {
  5348. return Engine._DELAYLOADSTATE_LOADING;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5354. get: function () {
  5355. return Engine._DELAYLOADSTATE_NOTLOADED;
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5361. get: function () {
  5362. return Engine._TEXTUREFORMAT_ALPHA;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5368. get: function () {
  5369. return Engine._TEXTUREFORMAT_LUMINANCE;
  5370. },
  5371. enumerable: true,
  5372. configurable: true
  5373. });
  5374. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5375. get: function () {
  5376. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5377. },
  5378. enumerable: true,
  5379. configurable: true
  5380. });
  5381. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5382. get: function () {
  5383. return Engine._TEXTUREFORMAT_RGB;
  5384. },
  5385. enumerable: true,
  5386. configurable: true
  5387. });
  5388. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5389. get: function () {
  5390. return Engine._TEXTUREFORMAT_RGBA;
  5391. },
  5392. enumerable: true,
  5393. configurable: true
  5394. });
  5395. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5396. get: function () {
  5397. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5398. },
  5399. enumerable: true,
  5400. configurable: true
  5401. });
  5402. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5403. get: function () {
  5404. return Engine._TEXTURETYPE_FLOAT;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(Engine, "Version", {
  5410. get: function () {
  5411. return "2.3.0-alpha";
  5412. },
  5413. enumerable: true,
  5414. configurable: true
  5415. });
  5416. Engine.prototype._prepareWorkingCanvas = function () {
  5417. if (this._workingCanvas) {
  5418. return;
  5419. }
  5420. this._workingCanvas = document.createElement("canvas");
  5421. this._workingContext = this._workingCanvas.getContext("2d");
  5422. };
  5423. Engine.prototype.resetTextureCache = function () {
  5424. for (var index = 0; index < this._maxTextureChannels; index++) {
  5425. this._activeTexturesCache[index] = null;
  5426. }
  5427. };
  5428. Engine.prototype.getGlInfo = function () {
  5429. return {
  5430. vendor: this._glVendor,
  5431. renderer: this._glRenderer,
  5432. version: this._glVersion
  5433. };
  5434. };
  5435. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5436. if (useScreen === void 0) { useScreen = false; }
  5437. var viewport = camera.viewport;
  5438. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5439. };
  5440. Engine.prototype.getRenderWidth = function (useScreen) {
  5441. if (useScreen === void 0) { useScreen = false; }
  5442. if (!useScreen && this._currentRenderTarget) {
  5443. return this._currentRenderTarget._width;
  5444. }
  5445. return this._renderingCanvas.width;
  5446. };
  5447. Engine.prototype.getRenderHeight = function (useScreen) {
  5448. if (useScreen === void 0) { useScreen = false; }
  5449. if (!useScreen && this._currentRenderTarget) {
  5450. return this._currentRenderTarget._height;
  5451. }
  5452. return this._renderingCanvas.height;
  5453. };
  5454. Engine.prototype.getRenderingCanvas = function () {
  5455. return this._renderingCanvas;
  5456. };
  5457. Engine.prototype.getRenderingCanvasClientRect = function () {
  5458. return this._renderingCanvas.getBoundingClientRect();
  5459. };
  5460. Engine.prototype.setHardwareScalingLevel = function (level) {
  5461. this._hardwareScalingLevel = level;
  5462. this.resize();
  5463. };
  5464. Engine.prototype.getHardwareScalingLevel = function () {
  5465. return this._hardwareScalingLevel;
  5466. };
  5467. Engine.prototype.getLoadedTexturesCache = function () {
  5468. return this._loadedTexturesCache;
  5469. };
  5470. Engine.prototype.getCaps = function () {
  5471. return this._caps;
  5472. };
  5473. Object.defineProperty(Engine.prototype, "drawCalls", {
  5474. get: function () {
  5475. return this._drawCalls;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. // Methods
  5481. Engine.prototype.resetDrawCalls = function () {
  5482. this._drawCalls = 0;
  5483. };
  5484. Engine.prototype.setDepthFunctionToGreater = function () {
  5485. this._depthCullingState.depthFunc = this._gl.GREATER;
  5486. };
  5487. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5488. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5489. };
  5490. Engine.prototype.setDepthFunctionToLess = function () {
  5491. this._depthCullingState.depthFunc = this._gl.LESS;
  5492. };
  5493. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5494. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5495. };
  5496. /**
  5497. * stop executing a render loop function and remove it from the execution array
  5498. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5499. */
  5500. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5501. if (!renderFunction) {
  5502. this._activeRenderLoops = [];
  5503. return;
  5504. }
  5505. var index = this._activeRenderLoops.indexOf(renderFunction);
  5506. if (index >= 0) {
  5507. this._activeRenderLoops.splice(index, 1);
  5508. }
  5509. };
  5510. Engine.prototype._renderLoop = function () {
  5511. var shouldRender = true;
  5512. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5513. shouldRender = false;
  5514. }
  5515. if (shouldRender) {
  5516. // Start new frame
  5517. this.beginFrame();
  5518. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5519. var renderFunction = this._activeRenderLoops[index];
  5520. renderFunction();
  5521. }
  5522. // Present
  5523. this.endFrame();
  5524. }
  5525. if (this._activeRenderLoops.length > 0) {
  5526. // Register new frame
  5527. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5528. }
  5529. else {
  5530. this._renderingQueueLaunched = false;
  5531. }
  5532. };
  5533. /**
  5534. * Register and execute a render loop. The engine can have more than one render function.
  5535. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5536. * @example
  5537. * engine.runRenderLoop(function () {
  5538. * scene.render()
  5539. * })
  5540. */
  5541. Engine.prototype.runRenderLoop = function (renderFunction) {
  5542. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5543. return;
  5544. }
  5545. this._activeRenderLoops.push(renderFunction);
  5546. if (!this._renderingQueueLaunched) {
  5547. this._renderingQueueLaunched = true;
  5548. this._bindedRenderFunction = this._renderLoop.bind(this);
  5549. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5550. }
  5551. };
  5552. /**
  5553. * Toggle full screen mode.
  5554. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5555. */
  5556. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5557. if (this.isFullscreen) {
  5558. BABYLON.Tools.ExitFullscreen();
  5559. }
  5560. else {
  5561. this._pointerLockRequested = requestPointerLock;
  5562. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5563. }
  5564. };
  5565. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5566. this.applyStates();
  5567. if (backBuffer) {
  5568. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5569. }
  5570. if (depthStencil && this._depthCullingState.depthMask) {
  5571. this._gl.clearDepth(1.0);
  5572. }
  5573. var mode = 0;
  5574. if (backBuffer) {
  5575. mode |= this._gl.COLOR_BUFFER_BIT;
  5576. }
  5577. if (depthStencil && this._depthCullingState.depthMask) {
  5578. mode |= this._gl.DEPTH_BUFFER_BIT;
  5579. }
  5580. this._gl.clear(mode);
  5581. };
  5582. /**
  5583. * Set the WebGL's viewport
  5584. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5585. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5586. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5587. */
  5588. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5589. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5590. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5591. var x = viewport.x || 0;
  5592. var y = viewport.y || 0;
  5593. this._cachedViewport = viewport;
  5594. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5595. };
  5596. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5597. this._cachedViewport = null;
  5598. this._gl.viewport(x, y, width, height);
  5599. };
  5600. Engine.prototype.beginFrame = function () {
  5601. this._measureFps();
  5602. };
  5603. Engine.prototype.endFrame = function () {
  5604. //this.flushFramebuffer();
  5605. };
  5606. /**
  5607. * resize the view according to the canvas' size.
  5608. * @example
  5609. * window.addEventListener("resize", function () {
  5610. * engine.resize();
  5611. * });
  5612. */
  5613. Engine.prototype.resize = function () {
  5614. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5615. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5616. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5617. for (var index = 0; index < this.scenes.length; index++) {
  5618. var scene = this.scenes[index];
  5619. if (scene.debugLayer.isVisible()) {
  5620. scene.debugLayer._syncPositions();
  5621. }
  5622. }
  5623. };
  5624. /**
  5625. * force a specific size of the canvas
  5626. * @param {number} width - the new canvas' width
  5627. * @param {number} height - the new canvas' height
  5628. */
  5629. Engine.prototype.setSize = function (width, height) {
  5630. this._renderingCanvas.width = width;
  5631. this._renderingCanvas.height = height;
  5632. for (var index = 0; index < this.scenes.length; index++) {
  5633. var scene = this.scenes[index];
  5634. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5635. var cam = scene.cameras[camIndex];
  5636. cam._currentRenderId = 0;
  5637. }
  5638. }
  5639. };
  5640. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5641. this._currentRenderTarget = texture;
  5642. var gl = this._gl;
  5643. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5644. if (texture.isCube) {
  5645. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5646. }
  5647. else {
  5648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5649. }
  5650. this._gl.viewport(0, 0, texture._width, texture._height);
  5651. this.wipeCaches();
  5652. };
  5653. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5654. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5655. this._currentRenderTarget = null;
  5656. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5657. var gl = this._gl;
  5658. gl.bindTexture(gl.TEXTURE_2D, texture);
  5659. gl.generateMipmap(gl.TEXTURE_2D);
  5660. gl.bindTexture(gl.TEXTURE_2D, null);
  5661. }
  5662. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5663. };
  5664. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5665. if (texture.generateMipMaps) {
  5666. var gl = this._gl;
  5667. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5668. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5670. }
  5671. };
  5672. Engine.prototype.flushFramebuffer = function () {
  5673. this._gl.flush();
  5674. };
  5675. Engine.prototype.restoreDefaultFramebuffer = function () {
  5676. this._currentRenderTarget = null;
  5677. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5678. this.setViewport(this._cachedViewport);
  5679. this.wipeCaches();
  5680. };
  5681. // VBOs
  5682. Engine.prototype._resetVertexBufferBinding = function () {
  5683. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5684. this._cachedVertexBuffers = null;
  5685. };
  5686. Engine.prototype.createVertexBuffer = function (vertices) {
  5687. var vbo = this._gl.createBuffer();
  5688. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5689. if (vertices instanceof Float32Array) {
  5690. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5691. }
  5692. else {
  5693. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5694. }
  5695. this._resetVertexBufferBinding();
  5696. vbo.references = 1;
  5697. return vbo;
  5698. };
  5699. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5700. var vbo = this._gl.createBuffer();
  5701. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5702. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5703. this._resetVertexBufferBinding();
  5704. vbo.references = 1;
  5705. return vbo;
  5706. };
  5707. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5708. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5709. if (offset === undefined) {
  5710. offset = 0;
  5711. }
  5712. if (vertices instanceof Float32Array) {
  5713. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5714. }
  5715. else {
  5716. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5717. }
  5718. this._resetVertexBufferBinding();
  5719. };
  5720. Engine.prototype._resetIndexBufferBinding = function () {
  5721. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5722. this._cachedIndexBuffer = null;
  5723. };
  5724. Engine.prototype.createIndexBuffer = function (indices) {
  5725. var vbo = this._gl.createBuffer();
  5726. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5727. // Check for 32 bits indices
  5728. var arrayBuffer;
  5729. var need32Bits = false;
  5730. if (this._caps.uintIndices) {
  5731. for (var index = 0; index < indices.length; index++) {
  5732. if (indices[index] > 65535) {
  5733. need32Bits = true;
  5734. break;
  5735. }
  5736. }
  5737. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5738. }
  5739. else {
  5740. arrayBuffer = new Uint16Array(indices);
  5741. }
  5742. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5743. this._resetIndexBufferBinding();
  5744. vbo.references = 1;
  5745. vbo.is32Bits = need32Bits;
  5746. return vbo;
  5747. };
  5748. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5749. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5750. this._cachedVertexBuffers = vertexBuffer;
  5751. this._cachedEffectForVertexBuffers = effect;
  5752. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5753. var offset = 0;
  5754. for (var index = 0; index < vertexDeclaration.length; index++) {
  5755. var order = effect.getAttributeLocation(index);
  5756. if (order >= 0) {
  5757. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5758. }
  5759. offset += vertexDeclaration[index] * 4;
  5760. }
  5761. }
  5762. if (this._cachedIndexBuffer !== indexBuffer) {
  5763. this._cachedIndexBuffer = indexBuffer;
  5764. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5765. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5766. }
  5767. };
  5768. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5769. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5770. this._cachedVertexBuffers = vertexBuffers;
  5771. this._cachedEffectForVertexBuffers = effect;
  5772. var attributes = effect.getAttributesNames();
  5773. for (var index = 0; index < attributes.length; index++) {
  5774. var order = effect.getAttributeLocation(index);
  5775. if (order >= 0) {
  5776. var vertexBuffer = vertexBuffers[attributes[index]];
  5777. if (!vertexBuffer) {
  5778. continue;
  5779. }
  5780. var stride = vertexBuffer.getStrideSize();
  5781. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5782. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5783. }
  5784. }
  5785. }
  5786. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5787. this._cachedIndexBuffer = indexBuffer;
  5788. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5789. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5790. }
  5791. };
  5792. Engine.prototype._releaseBuffer = function (buffer) {
  5793. buffer.references--;
  5794. if (buffer.references === 0) {
  5795. this._gl.deleteBuffer(buffer);
  5796. return true;
  5797. }
  5798. return false;
  5799. };
  5800. Engine.prototype.createInstancesBuffer = function (capacity) {
  5801. var buffer = this._gl.createBuffer();
  5802. buffer.capacity = capacity;
  5803. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5804. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5805. return buffer;
  5806. };
  5807. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5808. this._gl.deleteBuffer(buffer);
  5809. };
  5810. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5811. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5813. for (var index = 0; index < 4; index++) {
  5814. var offsetLocation = offsetLocations[index];
  5815. this._gl.enableVertexAttribArray(offsetLocation);
  5816. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5817. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5818. }
  5819. };
  5820. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5821. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5822. for (var index = 0; index < 4; index++) {
  5823. var offsetLocation = offsetLocations[index];
  5824. this._gl.disableVertexAttribArray(offsetLocation);
  5825. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5826. }
  5827. };
  5828. Engine.prototype.applyStates = function () {
  5829. this._depthCullingState.apply(this._gl);
  5830. this._alphaState.apply(this._gl);
  5831. };
  5832. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5833. // Apply states
  5834. this.applyStates();
  5835. this._drawCalls++;
  5836. // Render
  5837. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5838. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5839. if (instancesCount) {
  5840. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5841. return;
  5842. }
  5843. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5844. };
  5845. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5846. // Apply states
  5847. this.applyStates();
  5848. this._drawCalls++;
  5849. if (instancesCount) {
  5850. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5851. return;
  5852. }
  5853. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5854. };
  5855. // Shaders
  5856. Engine.prototype._releaseEffect = function (effect) {
  5857. if (this._compiledEffects[effect._key]) {
  5858. delete this._compiledEffects[effect._key];
  5859. if (effect.getProgram()) {
  5860. this._gl.deleteProgram(effect.getProgram());
  5861. }
  5862. }
  5863. };
  5864. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5865. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5866. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5867. var name = vertex + "+" + fragment + "@" + defines;
  5868. if (this._compiledEffects[name]) {
  5869. return this._compiledEffects[name];
  5870. }
  5871. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5872. effect._key = name;
  5873. this._compiledEffects[name] = effect;
  5874. return effect;
  5875. };
  5876. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5877. if (uniformsNames === void 0) { uniformsNames = []; }
  5878. if (samplers === void 0) { samplers = []; }
  5879. if (defines === void 0) { defines = ""; }
  5880. return this.createEffect({
  5881. vertex: "particles",
  5882. fragmentElement: fragmentName
  5883. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5884. };
  5885. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5886. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5887. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5888. var shaderProgram = this._gl.createProgram();
  5889. this._gl.attachShader(shaderProgram, vertexShader);
  5890. this._gl.attachShader(shaderProgram, fragmentShader);
  5891. this._gl.linkProgram(shaderProgram);
  5892. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5893. if (!linked) {
  5894. var error = this._gl.getProgramInfoLog(shaderProgram);
  5895. if (error) {
  5896. throw new Error(error);
  5897. }
  5898. }
  5899. this._gl.deleteShader(vertexShader);
  5900. this._gl.deleteShader(fragmentShader);
  5901. return shaderProgram;
  5902. };
  5903. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5904. var results = [];
  5905. for (var index = 0; index < uniformsNames.length; index++) {
  5906. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5907. }
  5908. return results;
  5909. };
  5910. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5911. var results = [];
  5912. for (var index = 0; index < attributesNames.length; index++) {
  5913. try {
  5914. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5915. }
  5916. catch (e) {
  5917. results.push(-1);
  5918. }
  5919. }
  5920. return results;
  5921. };
  5922. Engine.prototype.enableEffect = function (effect) {
  5923. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5924. if (effect && effect.onBind) {
  5925. effect.onBind(effect);
  5926. }
  5927. return;
  5928. }
  5929. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5930. // Use program
  5931. this._gl.useProgram(effect.getProgram());
  5932. for (var i in this._vertexAttribArrays) {
  5933. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5934. continue;
  5935. }
  5936. this._vertexAttribArrays[i] = false;
  5937. this._gl.disableVertexAttribArray(i);
  5938. }
  5939. var attributesCount = effect.getAttributesCount();
  5940. for (var index = 0; index < attributesCount; index++) {
  5941. // Attributes
  5942. var order = effect.getAttributeLocation(index);
  5943. if (order >= 0) {
  5944. this._vertexAttribArrays[order] = true;
  5945. this._gl.enableVertexAttribArray(order);
  5946. }
  5947. }
  5948. this._currentEffect = effect;
  5949. if (effect.onBind) {
  5950. effect.onBind(effect);
  5951. }
  5952. };
  5953. Engine.prototype.setArray = function (uniform, array) {
  5954. if (!uniform)
  5955. return;
  5956. this._gl.uniform1fv(uniform, array);
  5957. };
  5958. Engine.prototype.setArray2 = function (uniform, array) {
  5959. if (!uniform || array.length % 2 !== 0)
  5960. return;
  5961. this._gl.uniform2fv(uniform, array);
  5962. };
  5963. Engine.prototype.setArray3 = function (uniform, array) {
  5964. if (!uniform || array.length % 3 !== 0)
  5965. return;
  5966. this._gl.uniform3fv(uniform, array);
  5967. };
  5968. Engine.prototype.setArray4 = function (uniform, array) {
  5969. if (!uniform || array.length % 4 !== 0)
  5970. return;
  5971. this._gl.uniform4fv(uniform, array);
  5972. };
  5973. Engine.prototype.setMatrices = function (uniform, matrices) {
  5974. if (!uniform)
  5975. return;
  5976. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5977. };
  5978. Engine.prototype.setMatrix = function (uniform, matrix) {
  5979. if (!uniform)
  5980. return;
  5981. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5982. };
  5983. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5984. if (!uniform)
  5985. return;
  5986. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5987. };
  5988. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5989. if (!uniform)
  5990. return;
  5991. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5992. };
  5993. Engine.prototype.setFloat = function (uniform, value) {
  5994. if (!uniform)
  5995. return;
  5996. this._gl.uniform1f(uniform, value);
  5997. };
  5998. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5999. if (!uniform)
  6000. return;
  6001. this._gl.uniform2f(uniform, x, y);
  6002. };
  6003. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6004. if (!uniform)
  6005. return;
  6006. this._gl.uniform3f(uniform, x, y, z);
  6007. };
  6008. Engine.prototype.setBool = function (uniform, bool) {
  6009. if (!uniform)
  6010. return;
  6011. this._gl.uniform1i(uniform, bool);
  6012. };
  6013. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6014. if (!uniform)
  6015. return;
  6016. this._gl.uniform4f(uniform, x, y, z, w);
  6017. };
  6018. Engine.prototype.setColor3 = function (uniform, color3) {
  6019. if (!uniform)
  6020. return;
  6021. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6022. };
  6023. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6024. if (!uniform)
  6025. return;
  6026. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6027. };
  6028. // States
  6029. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6030. if (zOffset === void 0) { zOffset = 0; }
  6031. if (reverseSide === void 0) { reverseSide = false; }
  6032. // Culling
  6033. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6034. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6035. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6036. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6037. if (culling) {
  6038. this._depthCullingState.cullFace = cullFace;
  6039. this._depthCullingState.cull = true;
  6040. }
  6041. else {
  6042. this._depthCullingState.cull = false;
  6043. }
  6044. }
  6045. // Z offset
  6046. this._depthCullingState.zOffset = zOffset;
  6047. };
  6048. Engine.prototype.setDepthBuffer = function (enable) {
  6049. this._depthCullingState.depthTest = enable;
  6050. };
  6051. Engine.prototype.getDepthWrite = function () {
  6052. return this._depthCullingState.depthMask;
  6053. };
  6054. Engine.prototype.setDepthWrite = function (enable) {
  6055. this._depthCullingState.depthMask = enable;
  6056. };
  6057. Engine.prototype.setColorWrite = function (enable) {
  6058. this._gl.colorMask(enable, enable, enable, enable);
  6059. };
  6060. Engine.prototype.setAlphaMode = function (mode) {
  6061. if (this._alphaMode === mode) {
  6062. return;
  6063. }
  6064. switch (mode) {
  6065. case Engine.ALPHA_DISABLE:
  6066. this.setDepthWrite(true);
  6067. this._alphaState.alphaBlend = false;
  6068. break;
  6069. case Engine.ALPHA_COMBINE:
  6070. this.setDepthWrite(false);
  6071. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6072. this._alphaState.alphaBlend = true;
  6073. break;
  6074. case Engine.ALPHA_ONEONE:
  6075. this.setDepthWrite(false);
  6076. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6077. this._alphaState.alphaBlend = true;
  6078. break;
  6079. case Engine.ALPHA_ADD:
  6080. this.setDepthWrite(false);
  6081. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6082. this._alphaState.alphaBlend = true;
  6083. break;
  6084. case Engine.ALPHA_SUBTRACT:
  6085. this.setDepthWrite(false);
  6086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6087. this._alphaState.alphaBlend = true;
  6088. break;
  6089. case Engine.ALPHA_MULTIPLY:
  6090. this.setDepthWrite(false);
  6091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6092. this._alphaState.alphaBlend = true;
  6093. break;
  6094. case Engine.ALPHA_MAXIMIZED:
  6095. this.setDepthWrite(false);
  6096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6097. this._alphaState.alphaBlend = true;
  6098. break;
  6099. }
  6100. this._alphaMode = mode;
  6101. };
  6102. Engine.prototype.getAlphaMode = function () {
  6103. return this._alphaMode;
  6104. };
  6105. Engine.prototype.setAlphaTesting = function (enable) {
  6106. this._alphaTest = enable;
  6107. };
  6108. Engine.prototype.getAlphaTesting = function () {
  6109. return this._alphaTest;
  6110. };
  6111. // Textures
  6112. Engine.prototype.wipeCaches = function () {
  6113. this.resetTextureCache();
  6114. this._currentEffect = null;
  6115. this._depthCullingState.reset();
  6116. this._alphaState.reset();
  6117. this._cachedVertexBuffers = null;
  6118. this._cachedIndexBuffer = null;
  6119. this._cachedEffectForVertexBuffers = null;
  6120. };
  6121. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6122. var gl = this._gl;
  6123. gl.bindTexture(gl.TEXTURE_2D, texture);
  6124. var magFilter = gl.NEAREST;
  6125. var minFilter = gl.NEAREST;
  6126. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6127. magFilter = gl.LINEAR;
  6128. minFilter = gl.LINEAR;
  6129. }
  6130. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6131. magFilter = gl.LINEAR;
  6132. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6133. }
  6134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6136. gl.bindTexture(gl.TEXTURE_2D, null);
  6137. texture.samplingMode = samplingMode;
  6138. };
  6139. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6140. var _this = this;
  6141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6142. if (onLoad === void 0) { onLoad = null; }
  6143. if (onError === void 0) { onError = null; }
  6144. if (buffer === void 0) { buffer = null; }
  6145. var texture = this._gl.createTexture();
  6146. var extension;
  6147. var fromData = false;
  6148. if (url.substr(0, 5) === "data:") {
  6149. fromData = true;
  6150. }
  6151. if (!fromData)
  6152. extension = url.substr(url.length - 4, 4).toLowerCase();
  6153. else {
  6154. var oldUrl = url;
  6155. fromData = oldUrl.split(':');
  6156. url = oldUrl;
  6157. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6158. }
  6159. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6160. var isTGA = (extension === ".tga");
  6161. scene._addPendingData(texture);
  6162. texture.url = url;
  6163. texture.noMipmap = noMipmap;
  6164. texture.references = 1;
  6165. texture.samplingMode = samplingMode;
  6166. this._loadedTexturesCache.push(texture);
  6167. var onerror = function () {
  6168. scene._removePendingData(texture);
  6169. if (onError) {
  6170. onError();
  6171. }
  6172. };
  6173. var callback;
  6174. if (isTGA) {
  6175. callback = function (arrayBuffer) {
  6176. var data = new Uint8Array(arrayBuffer);
  6177. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6178. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6179. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6180. if (onLoad) {
  6181. onLoad();
  6182. }
  6183. }, samplingMode);
  6184. };
  6185. if (!(fromData instanceof Array))
  6186. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6187. callback(arrayBuffer);
  6188. }, onerror, scene.database, true);
  6189. else
  6190. callback(buffer);
  6191. }
  6192. else if (isDDS) {
  6193. callback = function (data) {
  6194. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6195. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6196. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6197. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6198. if (onLoad) {
  6199. onLoad();
  6200. }
  6201. }, samplingMode);
  6202. };
  6203. if (!(fromData instanceof Array))
  6204. BABYLON.Tools.LoadFile(url, function (data) {
  6205. callback(data);
  6206. }, onerror, scene.database, true);
  6207. else
  6208. callback(buffer);
  6209. }
  6210. else {
  6211. var onload = function (img) {
  6212. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6213. var isPot = (img.width === potWidth && img.height === potHeight);
  6214. if (!isPot) {
  6215. _this._prepareWorkingCanvas();
  6216. _this._workingCanvas.width = potWidth;
  6217. _this._workingCanvas.height = potHeight;
  6218. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6219. _this._workingContext.imageSmoothingEnabled = false;
  6220. _this._workingContext.mozImageSmoothingEnabled = false;
  6221. _this._workingContext.oImageSmoothingEnabled = false;
  6222. _this._workingContext.webkitImageSmoothingEnabled = false;
  6223. _this._workingContext.msImageSmoothingEnabled = false;
  6224. }
  6225. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6226. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6227. _this._workingContext.imageSmoothingEnabled = true;
  6228. _this._workingContext.mozImageSmoothingEnabled = true;
  6229. _this._workingContext.oImageSmoothingEnabled = true;
  6230. _this._workingContext.webkitImageSmoothingEnabled = true;
  6231. _this._workingContext.msImageSmoothingEnabled = true;
  6232. }
  6233. }
  6234. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6235. if (onLoad) {
  6236. onLoad();
  6237. }
  6238. }, samplingMode);
  6239. };
  6240. if (!(fromData instanceof Array))
  6241. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6242. else
  6243. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6244. }
  6245. return texture;
  6246. };
  6247. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6248. if (compression === void 0) { compression = null; }
  6249. var internalFormat = this._gl.RGBA;
  6250. switch (format) {
  6251. case Engine.TEXTUREFORMAT_ALPHA:
  6252. internalFormat = this._gl.ALPHA;
  6253. break;
  6254. case Engine.TEXTUREFORMAT_LUMINANCE:
  6255. internalFormat = this._gl.LUMINANCE;
  6256. break;
  6257. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6258. internalFormat = this._gl.LUMINANCE_ALPHA;
  6259. break;
  6260. case Engine.TEXTUREFORMAT_RGB:
  6261. internalFormat = this._gl.RGB;
  6262. break;
  6263. case Engine.TEXTUREFORMAT_RGBA:
  6264. internalFormat = this._gl.RGBA;
  6265. break;
  6266. }
  6267. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6268. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6269. if (compression) {
  6270. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6271. }
  6272. else {
  6273. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6274. }
  6275. if (texture.generateMipMaps) {
  6276. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6277. }
  6278. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6279. this.resetTextureCache();
  6280. texture.isReady = true;
  6281. };
  6282. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6283. if (compression === void 0) { compression = null; }
  6284. var texture = this._gl.createTexture();
  6285. texture._baseWidth = width;
  6286. texture._baseHeight = height;
  6287. texture._width = width;
  6288. texture._height = height;
  6289. texture.references = 1;
  6290. this.updateRawTexture(texture, data, format, invertY, compression);
  6291. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6292. // Filters
  6293. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6295. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6296. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6297. texture.samplingMode = samplingMode;
  6298. this._loadedTexturesCache.push(texture);
  6299. return texture;
  6300. };
  6301. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6302. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6303. var texture = this._gl.createTexture();
  6304. texture._baseWidth = width;
  6305. texture._baseHeight = height;
  6306. if (forceExponantOfTwo) {
  6307. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6308. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6309. }
  6310. this.resetTextureCache();
  6311. texture._width = width;
  6312. texture._height = height;
  6313. texture.isReady = false;
  6314. texture.generateMipMaps = generateMipMaps;
  6315. texture.references = 1;
  6316. texture.samplingMode = samplingMode;
  6317. this.updateTextureSamplingMode(samplingMode, texture);
  6318. this._loadedTexturesCache.push(texture);
  6319. return texture;
  6320. };
  6321. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6322. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6323. if (texture.isCube) {
  6324. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6325. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6326. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6327. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6328. }
  6329. else {
  6330. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6333. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6334. }
  6335. };
  6336. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6337. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6338. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6339. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6340. if (texture.generateMipMaps) {
  6341. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6342. }
  6343. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6344. this.resetTextureCache();
  6345. texture.isReady = true;
  6346. };
  6347. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6348. if (texture._isDisabled) {
  6349. return;
  6350. }
  6351. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6352. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6353. try {
  6354. // Testing video texture support
  6355. if (this._videoTextureSupported === undefined) {
  6356. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6357. if (this._gl.getError() !== 0) {
  6358. this._videoTextureSupported = false;
  6359. }
  6360. else {
  6361. this._videoTextureSupported = true;
  6362. }
  6363. }
  6364. // Copy video through the current working canvas if video texture is not supported
  6365. if (!this._videoTextureSupported) {
  6366. if (!texture._workingCanvas) {
  6367. texture._workingCanvas = document.createElement("canvas");
  6368. texture._workingContext = texture._workingCanvas.getContext("2d");
  6369. texture._workingCanvas.width = texture._width;
  6370. texture._workingCanvas.height = texture._height;
  6371. }
  6372. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6373. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6374. }
  6375. else {
  6376. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6377. }
  6378. if (texture.generateMipMaps) {
  6379. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6380. }
  6381. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6382. this.resetTextureCache();
  6383. texture.isReady = true;
  6384. }
  6385. catch (ex) {
  6386. // Something unexpected
  6387. // Let's disable the texture
  6388. texture._isDisabled = true;
  6389. }
  6390. };
  6391. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6392. // old version had a "generateMipMaps" arg instead of options.
  6393. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6394. // in the same way, generateDepthBuffer is defaulted to true
  6395. var generateMipMaps = false;
  6396. var generateDepthBuffer = true;
  6397. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6398. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6399. if (options !== undefined) {
  6400. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6401. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6402. type = options.type === undefined ? type : options.type;
  6403. if (options.samplingMode !== undefined) {
  6404. samplingMode = options.samplingMode;
  6405. }
  6406. if (type === Engine.TEXTURETYPE_FLOAT) {
  6407. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6408. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6409. }
  6410. }
  6411. var gl = this._gl;
  6412. var texture = gl.createTexture();
  6413. gl.bindTexture(gl.TEXTURE_2D, texture);
  6414. var width = size.width || size;
  6415. var height = size.height || size;
  6416. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6417. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6418. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6419. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6420. }
  6421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6425. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6426. var depthBuffer;
  6427. // Create the depth buffer
  6428. if (generateDepthBuffer) {
  6429. depthBuffer = gl.createRenderbuffer();
  6430. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6431. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6432. }
  6433. // Create the framebuffer
  6434. var framebuffer = gl.createFramebuffer();
  6435. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6436. if (generateDepthBuffer) {
  6437. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6438. }
  6439. if (generateMipMaps) {
  6440. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6441. }
  6442. // Unbind
  6443. gl.bindTexture(gl.TEXTURE_2D, null);
  6444. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6445. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6446. texture._framebuffer = framebuffer;
  6447. if (generateDepthBuffer) {
  6448. texture._depthBuffer = depthBuffer;
  6449. }
  6450. texture._width = width;
  6451. texture._height = height;
  6452. texture.isReady = true;
  6453. texture.generateMipMaps = generateMipMaps;
  6454. texture.references = 1;
  6455. texture.samplingMode = samplingMode;
  6456. this.resetTextureCache();
  6457. this._loadedTexturesCache.push(texture);
  6458. return texture;
  6459. };
  6460. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6461. var gl = this._gl;
  6462. var texture = gl.createTexture();
  6463. var generateMipMaps = true;
  6464. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6465. if (options !== undefined) {
  6466. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6467. if (options.samplingMode !== undefined) {
  6468. samplingMode = options.samplingMode;
  6469. }
  6470. }
  6471. texture.isCube = true;
  6472. texture.references = 1;
  6473. texture.generateMipMaps = generateMipMaps;
  6474. texture.references = 1;
  6475. texture.samplingMode = samplingMode;
  6476. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6477. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6478. for (var face = 0; face < 6; face++) {
  6479. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6480. }
  6481. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6482. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6485. // Create the depth buffer
  6486. var depthBuffer = gl.createRenderbuffer();
  6487. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6488. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6489. // Create the framebuffer
  6490. var framebuffer = gl.createFramebuffer();
  6491. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6492. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6493. // mipmaps
  6494. if (texture.generateMipMaps) {
  6495. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6496. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6497. }
  6498. // Unbind
  6499. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6500. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6501. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6502. texture._framebuffer = framebuffer;
  6503. texture._depthBuffer = depthBuffer;
  6504. this.resetTextureCache();
  6505. texture._width = size;
  6506. texture._height = size;
  6507. texture.isReady = true;
  6508. return texture;
  6509. };
  6510. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6511. var _this = this;
  6512. var gl = this._gl;
  6513. var texture = gl.createTexture();
  6514. texture.isCube = true;
  6515. texture.url = rootUrl;
  6516. texture.references = 1;
  6517. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6518. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6519. if (isDDS) {
  6520. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6521. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6522. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6523. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6524. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6525. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6526. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6527. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6528. }
  6529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6532. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6533. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6534. _this.resetTextureCache();
  6535. texture._width = info.width;
  6536. texture._height = info.height;
  6537. texture.isReady = true;
  6538. }, null, null, true);
  6539. }
  6540. else {
  6541. cascadeLoad(rootUrl, scene, function (imgs) {
  6542. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6543. var height = width;
  6544. _this._prepareWorkingCanvas();
  6545. _this._workingCanvas.width = width;
  6546. _this._workingCanvas.height = height;
  6547. var faces = [
  6548. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6549. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6550. ];
  6551. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6552. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6553. for (var index = 0; index < faces.length; index++) {
  6554. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6555. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6556. }
  6557. if (!noMipmap) {
  6558. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6559. }
  6560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6564. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6565. _this.resetTextureCache();
  6566. texture._width = width;
  6567. texture._height = height;
  6568. texture.isReady = true;
  6569. }, extensions);
  6570. }
  6571. return texture;
  6572. };
  6573. Engine.prototype._releaseTexture = function (texture) {
  6574. var gl = this._gl;
  6575. if (texture._framebuffer) {
  6576. gl.deleteFramebuffer(texture._framebuffer);
  6577. }
  6578. if (texture._depthBuffer) {
  6579. gl.deleteRenderbuffer(texture._depthBuffer);
  6580. }
  6581. gl.deleteTexture(texture);
  6582. // Unbind channels
  6583. this.unbindAllTextures();
  6584. var index = this._loadedTexturesCache.indexOf(texture);
  6585. if (index !== -1) {
  6586. this._loadedTexturesCache.splice(index, 1);
  6587. }
  6588. };
  6589. Engine.prototype.bindSamplers = function (effect) {
  6590. this._gl.useProgram(effect.getProgram());
  6591. var samplers = effect.getSamplers();
  6592. for (var index = 0; index < samplers.length; index++) {
  6593. var uniform = effect.getUniform(samplers[index]);
  6594. this._gl.uniform1i(uniform, index);
  6595. }
  6596. this._currentEffect = null;
  6597. };
  6598. Engine.prototype._bindTexture = function (channel, texture) {
  6599. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6601. this._activeTexturesCache[channel] = null;
  6602. };
  6603. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6604. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6605. };
  6606. Engine.prototype.unbindAllTextures = function () {
  6607. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6608. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6611. this._activeTexturesCache[channel] = null;
  6612. }
  6613. };
  6614. Engine.prototype.setTexture = function (channel, texture) {
  6615. if (channel < 0) {
  6616. return;
  6617. }
  6618. // Not ready?
  6619. if (!texture || !texture.isReady()) {
  6620. if (this._activeTexturesCache[channel] != null) {
  6621. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6622. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6623. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6624. this._activeTexturesCache[channel] = null;
  6625. }
  6626. return;
  6627. }
  6628. // Video
  6629. var alreadyActivated = false;
  6630. if (texture instanceof BABYLON.VideoTexture) {
  6631. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6632. alreadyActivated = true;
  6633. texture.update();
  6634. }
  6635. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6636. texture.delayLoad();
  6637. return;
  6638. }
  6639. if (this._activeTexturesCache[channel] === texture) {
  6640. return;
  6641. }
  6642. this._activeTexturesCache[channel] = texture;
  6643. var internalTexture = texture.getInternalTexture();
  6644. if (!alreadyActivated) {
  6645. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6646. }
  6647. if (internalTexture.isCube) {
  6648. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6649. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6650. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6651. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6652. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6653. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6654. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6655. }
  6656. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6657. }
  6658. else {
  6659. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6660. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6661. internalTexture._cachedWrapU = texture.wrapU;
  6662. switch (texture.wrapU) {
  6663. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6664. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6665. break;
  6666. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6668. break;
  6669. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6671. break;
  6672. }
  6673. }
  6674. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6675. internalTexture._cachedWrapV = texture.wrapV;
  6676. switch (texture.wrapV) {
  6677. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6678. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6679. break;
  6680. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6682. break;
  6683. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6685. break;
  6686. }
  6687. }
  6688. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6689. }
  6690. };
  6691. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6692. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6693. var value = texture.anisotropicFilteringLevel;
  6694. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6695. value = 1;
  6696. }
  6697. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6698. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6699. texture._cachedAnisotropicFilteringLevel = value;
  6700. }
  6701. };
  6702. Engine.prototype.readPixels = function (x, y, width, height) {
  6703. var data = new Uint8Array(height * width * 4);
  6704. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6705. return data;
  6706. };
  6707. Engine.prototype.releaseInternalTexture = function (texture) {
  6708. if (!texture) {
  6709. return;
  6710. }
  6711. texture.references--;
  6712. // Final reference ?
  6713. if (texture.references === 0) {
  6714. var texturesCache = this.getLoadedTexturesCache();
  6715. var index = texturesCache.indexOf(texture);
  6716. if (index > -1) {
  6717. texturesCache.splice(index, 1);
  6718. }
  6719. this._releaseTexture(texture);
  6720. }
  6721. };
  6722. // Dispose
  6723. Engine.prototype.dispose = function () {
  6724. this.hideLoadingUI();
  6725. this.stopRenderLoop();
  6726. // Release scenes
  6727. while (this.scenes.length) {
  6728. this.scenes[0].dispose();
  6729. }
  6730. // Release audio engine
  6731. Engine.audioEngine.dispose();
  6732. // Release effects
  6733. for (var name in this._compiledEffects) {
  6734. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6735. }
  6736. // Unbind
  6737. for (var i in this._vertexAttribArrays) {
  6738. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6739. continue;
  6740. }
  6741. this._gl.disableVertexAttribArray(i);
  6742. }
  6743. this._gl = null;
  6744. // Events
  6745. window.removeEventListener("blur", this._onBlur);
  6746. window.removeEventListener("focus", this._onFocus);
  6747. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6748. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6749. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6750. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6751. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6752. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6753. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6754. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6755. };
  6756. // Loading screen
  6757. Engine.prototype.displayLoadingUI = function () {
  6758. this._loadingScreen.displayLoadingUI();
  6759. };
  6760. Engine.prototype.hideLoadingUI = function () {
  6761. this._loadingScreen.hideLoadingUI();
  6762. };
  6763. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6764. get: function () {
  6765. return this._loadingScreen;
  6766. },
  6767. set: function (loadingScreen) {
  6768. this._loadingScreen = loadingScreen;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6774. set: function (text) {
  6775. this._loadingScreen.loadingUIText = text;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6781. set: function (color) {
  6782. this._loadingScreen.loadingUIBackgroundColor = color;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. // FPS
  6788. Engine.prototype.getFps = function () {
  6789. return this.fps;
  6790. };
  6791. Engine.prototype.getDeltaTime = function () {
  6792. return this.deltaTime;
  6793. };
  6794. Engine.prototype._measureFps = function () {
  6795. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6796. var length = this.previousFramesDuration.length;
  6797. if (length >= 2) {
  6798. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6799. }
  6800. if (length >= this.fpsRange) {
  6801. if (length > this.fpsRange) {
  6802. this.previousFramesDuration.splice(0, 1);
  6803. length = this.previousFramesDuration.length;
  6804. }
  6805. var sum = 0;
  6806. for (var id = 0; id < length - 1; id++) {
  6807. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6808. }
  6809. this.fps = 1000.0 / (sum / (length - 1));
  6810. }
  6811. };
  6812. // Statics
  6813. Engine.isSupported = function () {
  6814. try {
  6815. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6816. if (navigator.isCocoonJS) {
  6817. return true;
  6818. }
  6819. var tempcanvas = document.createElement("canvas");
  6820. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6821. return gl != null && !!window.WebGLRenderingContext;
  6822. }
  6823. catch (e) {
  6824. return false;
  6825. }
  6826. };
  6827. // Const statics
  6828. Engine._ALPHA_DISABLE = 0;
  6829. Engine._ALPHA_ADD = 1;
  6830. Engine._ALPHA_COMBINE = 2;
  6831. Engine._ALPHA_SUBTRACT = 3;
  6832. Engine._ALPHA_MULTIPLY = 4;
  6833. Engine._ALPHA_MAXIMIZED = 5;
  6834. Engine._ALPHA_ONEONE = 6;
  6835. Engine._DELAYLOADSTATE_NONE = 0;
  6836. Engine._DELAYLOADSTATE_LOADED = 1;
  6837. Engine._DELAYLOADSTATE_LOADING = 2;
  6838. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6839. Engine._TEXTUREFORMAT_ALPHA = 0;
  6840. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6841. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6842. Engine._TEXTUREFORMAT_RGB = 4;
  6843. Engine._TEXTUREFORMAT_RGBA = 5;
  6844. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6845. Engine._TEXTURETYPE_FLOAT = 1;
  6846. // Updatable statics so stick with vars here
  6847. Engine.Epsilon = 0.001;
  6848. Engine.CollisionsEpsilon = 0.001;
  6849. Engine.CodeRepository = "src/";
  6850. Engine.ShadersRepository = "src/Shaders/";
  6851. return Engine;
  6852. })();
  6853. BABYLON.Engine = Engine;
  6854. })(BABYLON || (BABYLON = {}));
  6855. var BABYLON;
  6856. (function (BABYLON) {
  6857. /**
  6858. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6859. */
  6860. var Node = (function () {
  6861. /**
  6862. * @constructor
  6863. * @param {string} name - the name and id to be given to this node
  6864. * @param {BABYLON.Scene} the scene this node will be added to
  6865. */
  6866. function Node(name, scene) {
  6867. this.state = "";
  6868. this.animations = new Array();
  6869. this._childrenFlag = -1;
  6870. this._isEnabled = true;
  6871. this._isReady = true;
  6872. this._currentRenderId = -1;
  6873. this._parentRenderId = -1;
  6874. this.name = name;
  6875. this.id = name;
  6876. this._scene = scene;
  6877. this._initCache();
  6878. }
  6879. Node.prototype.getScene = function () {
  6880. return this._scene;
  6881. };
  6882. Node.prototype.getEngine = function () {
  6883. return this._scene.getEngine();
  6884. };
  6885. // override it in derived class
  6886. Node.prototype.getWorldMatrix = function () {
  6887. return BABYLON.Matrix.Identity();
  6888. };
  6889. // override it in derived class if you add new variables to the cache
  6890. // and call the parent class method
  6891. Node.prototype._initCache = function () {
  6892. this._cache = {};
  6893. this._cache.parent = undefined;
  6894. };
  6895. Node.prototype.updateCache = function (force) {
  6896. if (!force && this.isSynchronized())
  6897. return;
  6898. this._cache.parent = this.parent;
  6899. this._updateCache();
  6900. };
  6901. // override it in derived class if you add new variables to the cache
  6902. // and call the parent class method if !ignoreParentClass
  6903. Node.prototype._updateCache = function (ignoreParentClass) {
  6904. };
  6905. // override it in derived class if you add new variables to the cache
  6906. Node.prototype._isSynchronized = function () {
  6907. return true;
  6908. };
  6909. Node.prototype._markSyncedWithParent = function () {
  6910. this._parentRenderId = this.parent._currentRenderId;
  6911. };
  6912. Node.prototype.isSynchronizedWithParent = function () {
  6913. if (!this.parent) {
  6914. return true;
  6915. }
  6916. if (this._parentRenderId !== this.parent._currentRenderId) {
  6917. return false;
  6918. }
  6919. return this.parent.isSynchronized();
  6920. };
  6921. Node.prototype.isSynchronized = function (updateCache) {
  6922. var check = this.hasNewParent();
  6923. check = check || !this.isSynchronizedWithParent();
  6924. check = check || !this._isSynchronized();
  6925. if (updateCache)
  6926. this.updateCache(true);
  6927. return !check;
  6928. };
  6929. Node.prototype.hasNewParent = function (update) {
  6930. if (this._cache.parent === this.parent)
  6931. return false;
  6932. if (update)
  6933. this._cache.parent = this.parent;
  6934. return true;
  6935. };
  6936. /**
  6937. * Is this node ready to be used/rendered
  6938. * @return {boolean} is it ready
  6939. */
  6940. Node.prototype.isReady = function () {
  6941. return this._isReady;
  6942. };
  6943. /**
  6944. * Is this node enabled.
  6945. * If the node has a parent and is enabled, the parent will be inspected as well.
  6946. * @return {boolean} whether this node (and its parent) is enabled.
  6947. * @see setEnabled
  6948. */
  6949. Node.prototype.isEnabled = function () {
  6950. if (!this._isEnabled) {
  6951. return false;
  6952. }
  6953. if (this.parent) {
  6954. return this.parent.isEnabled();
  6955. }
  6956. return true;
  6957. };
  6958. /**
  6959. * Set the enabled state of this node.
  6960. * @param {boolean} value - the new enabled state
  6961. * @see isEnabled
  6962. */
  6963. Node.prototype.setEnabled = function (value) {
  6964. this._isEnabled = value;
  6965. };
  6966. /**
  6967. * Is this node a descendant of the given node.
  6968. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6969. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6970. * @see parent
  6971. */
  6972. Node.prototype.isDescendantOf = function (ancestor) {
  6973. if (this.parent) {
  6974. if (this.parent === ancestor) {
  6975. return true;
  6976. }
  6977. return this.parent.isDescendantOf(ancestor);
  6978. }
  6979. return false;
  6980. };
  6981. Node.prototype._getDescendants = function (list, results) {
  6982. for (var index = 0; index < list.length; index++) {
  6983. var item = list[index];
  6984. if (item.isDescendantOf(this)) {
  6985. results.push(item);
  6986. }
  6987. }
  6988. };
  6989. /**
  6990. * Will return all nodes that have this node as parent.
  6991. * @return {BABYLON.Node[]} all children nodes of all types.
  6992. */
  6993. Node.prototype.getDescendants = function () {
  6994. var results = [];
  6995. this._getDescendants(this._scene.meshes, results);
  6996. this._getDescendants(this._scene.lights, results);
  6997. this._getDescendants(this._scene.cameras, results);
  6998. return results;
  6999. };
  7000. Node.prototype._setReady = function (state) {
  7001. if (state === this._isReady) {
  7002. return;
  7003. }
  7004. if (!state) {
  7005. this._isReady = false;
  7006. return;
  7007. }
  7008. this._isReady = true;
  7009. if (this.onReady) {
  7010. this.onReady(this);
  7011. }
  7012. };
  7013. Node.prototype.getAnimationByName = function (name) {
  7014. for (var i = 0; i < this.animations.length; i++) {
  7015. var animation = this.animations[i];
  7016. if (animation.name === name) {
  7017. return animation;
  7018. }
  7019. }
  7020. return null;
  7021. };
  7022. return Node;
  7023. })();
  7024. BABYLON.Node = Node;
  7025. })(BABYLON || (BABYLON = {}));
  7026. var BABYLON;
  7027. (function (BABYLON) {
  7028. var FilesInput = (function () {
  7029. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7030. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7031. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7032. this._engine = p_engine;
  7033. this._canvas = p_canvas;
  7034. this._currentScene = p_scene;
  7035. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7036. this._progressCallback = p_progressCallback;
  7037. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7038. this._textureLoadingCallback = p_textureLoadingCallback;
  7039. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7040. }
  7041. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7042. var _this = this;
  7043. if (p_elementToMonitor) {
  7044. this._elementToMonitor = p_elementToMonitor;
  7045. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7046. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7047. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7048. }
  7049. };
  7050. FilesInput.prototype.renderFunction = function () {
  7051. if (this._additionnalRenderLoopLogicCallback) {
  7052. this._additionnalRenderLoopLogicCallback();
  7053. }
  7054. if (this._currentScene) {
  7055. if (this._textureLoadingCallback) {
  7056. var remaining = this._currentScene.getWaitingItemsCount();
  7057. if (remaining > 0) {
  7058. this._textureLoadingCallback(remaining);
  7059. }
  7060. }
  7061. this._currentScene.render();
  7062. }
  7063. };
  7064. FilesInput.prototype.drag = function (e) {
  7065. e.stopPropagation();
  7066. e.preventDefault();
  7067. };
  7068. FilesInput.prototype.drop = function (eventDrop) {
  7069. eventDrop.stopPropagation();
  7070. eventDrop.preventDefault();
  7071. this.loadFiles(eventDrop);
  7072. };
  7073. FilesInput.prototype.loadFiles = function (event) {
  7074. if (this._startingProcessingFilesCallback)
  7075. this._startingProcessingFilesCallback();
  7076. // Handling data transfer via drag'n'drop
  7077. if (event && event.dataTransfer && event.dataTransfer.files) {
  7078. this._filesToLoad = event.dataTransfer.files;
  7079. }
  7080. // Handling files from input files
  7081. if (event && event.target && event.target.files) {
  7082. this._filesToLoad = event.target.files;
  7083. }
  7084. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7085. for (var i = 0; i < this._filesToLoad.length; i++) {
  7086. switch (this._filesToLoad[i].type) {
  7087. case "image/jpeg":
  7088. case "image/png":
  7089. case "image/bmp":
  7090. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7091. break;
  7092. case "image/targa":
  7093. case "image/vnd.ms-dds":
  7094. case "audio/wav":
  7095. case "audio/x-wav":
  7096. case "audio/mp3":
  7097. case "audio/mpeg":
  7098. case "audio/mpeg3":
  7099. case "audio/x-mpeg-3":
  7100. case "audio/ogg":
  7101. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7102. break;
  7103. default:
  7104. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7105. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7106. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7107. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7108. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7109. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7110. this._sceneFileToLoad = this._filesToLoad[i];
  7111. }
  7112. break;
  7113. }
  7114. }
  7115. this.reload();
  7116. }
  7117. };
  7118. FilesInput.prototype.reload = function () {
  7119. var _this = this;
  7120. var that = this;
  7121. // If a ".babylon" file has been provided
  7122. if (this._sceneFileToLoad) {
  7123. if (this._currentScene) {
  7124. if (BABYLON.Tools.errorsCount > 0) {
  7125. BABYLON.Tools.ClearLogCache();
  7126. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7127. }
  7128. this._engine.stopRenderLoop();
  7129. this._currentScene.dispose();
  7130. }
  7131. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7132. that._currentScene = newScene;
  7133. // Wait for textures and shaders to be ready
  7134. that._currentScene.executeWhenReady(function () {
  7135. // Attach camera to canvas inputs
  7136. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7137. that._currentScene.createDefaultCameraOrLight();
  7138. }
  7139. that._currentScene.activeCamera.attachControl(that._canvas);
  7140. if (that._sceneLoadedCallback) {
  7141. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7142. }
  7143. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7144. });
  7145. }, function (progress) {
  7146. if (_this._progressCallback) {
  7147. _this._progressCallback(progress);
  7148. }
  7149. });
  7150. }
  7151. else {
  7152. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7153. }
  7154. };
  7155. FilesInput.FilesTextures = new Array();
  7156. FilesInput.FilesToLoad = new Array();
  7157. return FilesInput;
  7158. })();
  7159. BABYLON.FilesInput = FilesInput;
  7160. })(BABYLON || (BABYLON = {}));
  7161. var BABYLON;
  7162. (function (BABYLON) {
  7163. var IntersectionInfo = (function () {
  7164. function IntersectionInfo(bu, bv, distance) {
  7165. this.bu = bu;
  7166. this.bv = bv;
  7167. this.distance = distance;
  7168. this.faceId = 0;
  7169. this.subMeshId = 0;
  7170. }
  7171. return IntersectionInfo;
  7172. })();
  7173. BABYLON.IntersectionInfo = IntersectionInfo;
  7174. var PickingInfo = (function () {
  7175. function PickingInfo() {
  7176. this.hit = false;
  7177. this.distance = 0;
  7178. this.pickedPoint = null;
  7179. this.pickedMesh = null;
  7180. this.bu = 0;
  7181. this.bv = 0;
  7182. this.faceId = -1;
  7183. this.subMeshId = 0;
  7184. this.pickedSprite = null;
  7185. }
  7186. // Methods
  7187. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7188. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7189. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7190. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7191. return null;
  7192. }
  7193. var indices = this.pickedMesh.getIndices();
  7194. var result;
  7195. if (useVerticesNormals) {
  7196. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7197. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7198. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7199. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7200. normal0 = normal0.scale(this.bu);
  7201. normal1 = normal1.scale(this.bv);
  7202. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7203. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7204. }
  7205. else {
  7206. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7207. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7208. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7209. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7210. var p1p2 = vertex1.subtract(vertex2);
  7211. var p3p2 = vertex3.subtract(vertex2);
  7212. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7213. }
  7214. if (useWorldCoordinates) {
  7215. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7216. }
  7217. return BABYLON.Vector3.Normalize(result);
  7218. };
  7219. PickingInfo.prototype.getTextureCoordinates = function () {
  7220. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7221. return null;
  7222. }
  7223. var indices = this.pickedMesh.getIndices();
  7224. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7225. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7226. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7227. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7228. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7229. uv1 = uv1.scale(this.bu);
  7230. uv2 = uv2.scale(this.bv);
  7231. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7232. };
  7233. return PickingInfo;
  7234. })();
  7235. BABYLON.PickingInfo = PickingInfo;
  7236. })(BABYLON || (BABYLON = {}));
  7237. var BABYLON;
  7238. (function (BABYLON) {
  7239. var BoundingSphere = (function () {
  7240. function BoundingSphere(minimum, maximum) {
  7241. this.minimum = minimum;
  7242. this.maximum = maximum;
  7243. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7244. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7245. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7246. this.radius = distance * 0.5;
  7247. this.centerWorld = BABYLON.Vector3.Zero();
  7248. this._update(BABYLON.Matrix.Identity());
  7249. }
  7250. // Methods
  7251. BoundingSphere.prototype._update = function (world) {
  7252. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7253. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7254. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7255. };
  7256. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7257. for (var i = 0; i < 6; i++) {
  7258. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7259. return false;
  7260. }
  7261. return true;
  7262. };
  7263. BoundingSphere.prototype.intersectsPoint = function (point) {
  7264. var x = this.centerWorld.x - point.x;
  7265. var y = this.centerWorld.y - point.y;
  7266. var z = this.centerWorld.z - point.z;
  7267. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7268. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7269. return false;
  7270. return true;
  7271. };
  7272. // Statics
  7273. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7274. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7275. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7276. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7277. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7278. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7279. return false;
  7280. return true;
  7281. };
  7282. return BoundingSphere;
  7283. })();
  7284. BABYLON.BoundingSphere = BoundingSphere;
  7285. })(BABYLON || (BABYLON = {}));
  7286. var BABYLON;
  7287. (function (BABYLON) {
  7288. var BoundingBox = (function () {
  7289. function BoundingBox(minimum, maximum) {
  7290. this.minimum = minimum;
  7291. this.maximum = maximum;
  7292. this.vectors = new Array();
  7293. this.vectorsWorld = new Array();
  7294. // Bounding vectors
  7295. this.vectors.push(this.minimum.clone());
  7296. this.vectors.push(this.maximum.clone());
  7297. this.vectors.push(this.minimum.clone());
  7298. this.vectors[2].x = this.maximum.x;
  7299. this.vectors.push(this.minimum.clone());
  7300. this.vectors[3].y = this.maximum.y;
  7301. this.vectors.push(this.minimum.clone());
  7302. this.vectors[4].z = this.maximum.z;
  7303. this.vectors.push(this.maximum.clone());
  7304. this.vectors[5].z = this.minimum.z;
  7305. this.vectors.push(this.maximum.clone());
  7306. this.vectors[6].x = this.minimum.x;
  7307. this.vectors.push(this.maximum.clone());
  7308. this.vectors[7].y = this.minimum.y;
  7309. // OBB
  7310. this.center = this.maximum.add(this.minimum).scale(0.5);
  7311. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7312. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7313. // World
  7314. for (var index = 0; index < this.vectors.length; index++) {
  7315. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7316. }
  7317. this.minimumWorld = BABYLON.Vector3.Zero();
  7318. this.maximumWorld = BABYLON.Vector3.Zero();
  7319. this._update(BABYLON.Matrix.Identity());
  7320. }
  7321. // Methods
  7322. BoundingBox.prototype.getWorldMatrix = function () {
  7323. return this._worldMatrix;
  7324. };
  7325. BoundingBox.prototype._update = function (world) {
  7326. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7327. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7328. for (var index = 0; index < this.vectors.length; index++) {
  7329. var v = this.vectorsWorld[index];
  7330. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7331. if (v.x < this.minimumWorld.x)
  7332. this.minimumWorld.x = v.x;
  7333. if (v.y < this.minimumWorld.y)
  7334. this.minimumWorld.y = v.y;
  7335. if (v.z < this.minimumWorld.z)
  7336. this.minimumWorld.z = v.z;
  7337. if (v.x > this.maximumWorld.x)
  7338. this.maximumWorld.x = v.x;
  7339. if (v.y > this.maximumWorld.y)
  7340. this.maximumWorld.y = v.y;
  7341. if (v.z > this.maximumWorld.z)
  7342. this.maximumWorld.z = v.z;
  7343. }
  7344. // OBB
  7345. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7346. this.center.scaleInPlace(0.5);
  7347. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7348. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7349. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7350. this._worldMatrix = world;
  7351. };
  7352. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7353. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7354. };
  7355. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7356. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7357. };
  7358. BoundingBox.prototype.intersectsPoint = function (point) {
  7359. var delta = -BABYLON.Engine.Epsilon;
  7360. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7361. return false;
  7362. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7363. return false;
  7364. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7365. return false;
  7366. return true;
  7367. };
  7368. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7369. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7370. };
  7371. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7372. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7373. return false;
  7374. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7375. return false;
  7376. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7377. return false;
  7378. return true;
  7379. };
  7380. // Statics
  7381. BoundingBox.Intersects = function (box0, box1) {
  7382. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7383. return false;
  7384. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7385. return false;
  7386. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7387. return false;
  7388. return true;
  7389. };
  7390. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7391. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7392. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7393. return (num <= (sphereRadius * sphereRadius));
  7394. };
  7395. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7396. for (var p = 0; p < 6; p++) {
  7397. for (var i = 0; i < 8; i++) {
  7398. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7399. return false;
  7400. }
  7401. }
  7402. }
  7403. return true;
  7404. };
  7405. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7406. for (var p = 0; p < 6; p++) {
  7407. var inCount = 8;
  7408. for (var i = 0; i < 8; i++) {
  7409. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7410. --inCount;
  7411. }
  7412. else {
  7413. break;
  7414. }
  7415. }
  7416. if (inCount === 0)
  7417. return false;
  7418. }
  7419. return true;
  7420. };
  7421. return BoundingBox;
  7422. })();
  7423. BABYLON.BoundingBox = BoundingBox;
  7424. })(BABYLON || (BABYLON = {}));
  7425. var BABYLON;
  7426. (function (BABYLON) {
  7427. var computeBoxExtents = function (axis, box) {
  7428. var p = BABYLON.Vector3.Dot(box.center, axis);
  7429. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7430. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7431. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7432. var r = r0 + r1 + r2;
  7433. return {
  7434. min: p - r,
  7435. max: p + r
  7436. };
  7437. };
  7438. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7439. var axisOverlap = function (axis, box0, box1) {
  7440. var result0 = computeBoxExtents(axis, box0);
  7441. var result1 = computeBoxExtents(axis, box1);
  7442. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7443. };
  7444. var BoundingInfo = (function () {
  7445. function BoundingInfo(minimum, maximum) {
  7446. this.minimum = minimum;
  7447. this.maximum = maximum;
  7448. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7449. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7450. }
  7451. // Methods
  7452. BoundingInfo.prototype._update = function (world) {
  7453. this.boundingBox._update(world);
  7454. this.boundingSphere._update(world);
  7455. };
  7456. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7457. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7458. return false;
  7459. return this.boundingBox.isInFrustum(frustumPlanes);
  7460. };
  7461. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7462. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7463. };
  7464. BoundingInfo.prototype._checkCollision = function (collider) {
  7465. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7466. };
  7467. BoundingInfo.prototype.intersectsPoint = function (point) {
  7468. if (!this.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!this.boundingSphere.intersectsPoint(point)) {
  7472. return false;
  7473. }
  7474. if (!this.boundingBox.intersectsPoint(point)) {
  7475. return false;
  7476. }
  7477. return true;
  7478. };
  7479. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7480. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7481. return false;
  7482. }
  7483. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7484. return false;
  7485. }
  7486. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7487. return false;
  7488. }
  7489. if (!precise) {
  7490. return true;
  7491. }
  7492. var box0 = this.boundingBox;
  7493. var box1 = boundingInfo.boundingBox;
  7494. if (!axisOverlap(box0.directions[0], box0, box1))
  7495. return false;
  7496. if (!axisOverlap(box0.directions[1], box0, box1))
  7497. return false;
  7498. if (!axisOverlap(box0.directions[2], box0, box1))
  7499. return false;
  7500. if (!axisOverlap(box1.directions[0], box0, box1))
  7501. return false;
  7502. if (!axisOverlap(box1.directions[1], box0, box1))
  7503. return false;
  7504. if (!axisOverlap(box1.directions[2], box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7511. return false;
  7512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7513. return false;
  7514. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7515. return false;
  7516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7517. return false;
  7518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7519. return false;
  7520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7521. return false;
  7522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7523. return false;
  7524. return true;
  7525. };
  7526. return BoundingInfo;
  7527. })();
  7528. BABYLON.BoundingInfo = BoundingInfo;
  7529. })(BABYLON || (BABYLON = {}));
  7530. var BABYLON;
  7531. (function (BABYLON) {
  7532. var AbstractMesh = (function (_super) {
  7533. __extends(AbstractMesh, _super);
  7534. function AbstractMesh(name, scene) {
  7535. var _this = this;
  7536. _super.call(this, name, scene);
  7537. // Properties
  7538. this.definedFacingForward = true; // orientation for POV movement & rotation
  7539. this.position = new BABYLON.Vector3(0, 0, 0);
  7540. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7541. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7542. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7543. this.visibility = 1.0;
  7544. this.alphaIndex = Number.MAX_VALUE;
  7545. this.infiniteDistance = false;
  7546. this.isVisible = true;
  7547. this.isPickable = true;
  7548. this.showBoundingBox = false;
  7549. this.showSubMeshesBoundingBox = false;
  7550. this.onDispose = null;
  7551. this.isBlocker = false;
  7552. this.renderingGroupId = 0;
  7553. this.receiveShadows = false;
  7554. this.renderOutline = false;
  7555. this.outlineColor = BABYLON.Color3.Red();
  7556. this.outlineWidth = 0.02;
  7557. this.renderOverlay = false;
  7558. this.overlayColor = BABYLON.Color3.Red();
  7559. this.overlayAlpha = 0.5;
  7560. this.hasVertexAlpha = false;
  7561. this.useVertexColors = true;
  7562. this.applyFog = true;
  7563. this.computeBonesUsingShaders = true;
  7564. this.scalingDeterminant = 1;
  7565. this.numBoneInfluencers = 4;
  7566. this.useOctreeForRenderingSelection = true;
  7567. this.useOctreeForPicking = true;
  7568. this.useOctreeForCollisions = true;
  7569. this.layerMask = 0x0FFFFFFF;
  7570. this.alwaysSelectAsActiveMesh = false;
  7571. // Physics
  7572. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7573. // Collisions
  7574. this._checkCollisions = false;
  7575. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7576. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7577. this._collider = new BABYLON.Collider();
  7578. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7579. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7580. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7581. // Edges
  7582. this.edgesWidth = 1;
  7583. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7584. // Cache
  7585. this._localScaling = BABYLON.Matrix.Zero();
  7586. this._localRotation = BABYLON.Matrix.Zero();
  7587. this._localTranslation = BABYLON.Matrix.Zero();
  7588. this._localBillboard = BABYLON.Matrix.Zero();
  7589. this._localPivotScaling = BABYLON.Matrix.Zero();
  7590. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7591. this._localWorld = BABYLON.Matrix.Zero();
  7592. this._worldMatrix = BABYLON.Matrix.Zero();
  7593. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7594. this._absolutePosition = BABYLON.Vector3.Zero();
  7595. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7596. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7597. this._isDirty = false;
  7598. this._pivotMatrix = BABYLON.Matrix.Identity();
  7599. this._isDisposed = false;
  7600. this._renderId = 0;
  7601. this._intersectionsInProgress = new Array();
  7602. this._onAfterWorldMatrixUpdate = new Array();
  7603. this._isWorldMatrixFrozen = false;
  7604. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7605. if (collidedMesh === void 0) { collidedMesh = null; }
  7606. //TODO move this to the collision coordinator!
  7607. if (_this.getScene().workerCollisions)
  7608. newPosition.multiplyInPlace(_this._collider.radius);
  7609. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7610. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7611. _this.position.addInPlace(_this._diffPositionForCollisions);
  7612. }
  7613. if (_this.onCollide && collidedMesh) {
  7614. _this.onCollide(collidedMesh);
  7615. }
  7616. if (_this.onCollisionPositionChange) {
  7617. _this.onCollisionPositionChange(_this.position);
  7618. }
  7619. };
  7620. scene.addMesh(this);
  7621. }
  7622. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7623. get: function () {
  7624. return AbstractMesh._BILLBOARDMODE_NONE;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7630. get: function () {
  7631. return AbstractMesh._BILLBOARDMODE_X;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7637. get: function () {
  7638. return AbstractMesh._BILLBOARDMODE_Y;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7644. get: function () {
  7645. return AbstractMesh._BILLBOARDMODE_Z;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7651. get: function () {
  7652. return AbstractMesh._BILLBOARDMODE_ALL;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. // Methods
  7658. AbstractMesh.prototype.disableEdgesRendering = function () {
  7659. if (this._edgesRenderer !== undefined) {
  7660. this._edgesRenderer.dispose();
  7661. this._edgesRenderer = undefined;
  7662. }
  7663. };
  7664. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7665. if (epsilon === void 0) { epsilon = 0.95; }
  7666. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7667. this.disableEdgesRendering();
  7668. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7669. };
  7670. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7671. get: function () {
  7672. return false;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. AbstractMesh.prototype.getLOD = function (camera) {
  7678. return this;
  7679. };
  7680. AbstractMesh.prototype.getTotalVertices = function () {
  7681. return 0;
  7682. };
  7683. AbstractMesh.prototype.getIndices = function () {
  7684. return null;
  7685. };
  7686. AbstractMesh.prototype.getVerticesData = function (kind) {
  7687. return null;
  7688. };
  7689. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7690. return false;
  7691. };
  7692. AbstractMesh.prototype.getBoundingInfo = function () {
  7693. if (this._masterMesh) {
  7694. return this._masterMesh.getBoundingInfo();
  7695. }
  7696. if (!this._boundingInfo) {
  7697. this._updateBoundingInfo();
  7698. }
  7699. return this._boundingInfo;
  7700. };
  7701. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7702. get: function () {
  7703. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. AbstractMesh.prototype._preActivate = function () {
  7709. };
  7710. AbstractMesh.prototype._activate = function (renderId) {
  7711. this._renderId = renderId;
  7712. };
  7713. AbstractMesh.prototype.getWorldMatrix = function () {
  7714. if (this._masterMesh) {
  7715. return this._masterMesh.getWorldMatrix();
  7716. }
  7717. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7718. this.computeWorldMatrix();
  7719. }
  7720. return this._worldMatrix;
  7721. };
  7722. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7723. get: function () {
  7724. return this._worldMatrix;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7730. get: function () {
  7731. return this._absolutePosition;
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7737. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7738. this.computeWorldMatrix(true);
  7739. this._isWorldMatrixFrozen = true;
  7740. };
  7741. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7742. this._isWorldMatrixFrozen = false;
  7743. this.computeWorldMatrix(true);
  7744. };
  7745. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7746. get: function () {
  7747. return this._isWorldMatrixFrozen;
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7753. axis.normalize();
  7754. if (!this.rotationQuaternion) {
  7755. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7756. this.rotation = BABYLON.Vector3.Zero();
  7757. }
  7758. var rotationQuaternion;
  7759. if (!space || space === BABYLON.Space.LOCAL) {
  7760. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7761. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7762. }
  7763. else {
  7764. if (this.parent) {
  7765. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7766. invertParentWorldMatrix.invert();
  7767. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7768. }
  7769. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7770. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7771. }
  7772. };
  7773. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7774. var displacementVector = axis.scale(distance);
  7775. if (!space || space === BABYLON.Space.LOCAL) {
  7776. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7777. this.setPositionWithLocalVector(tempV3);
  7778. }
  7779. else {
  7780. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7781. }
  7782. };
  7783. AbstractMesh.prototype.getAbsolutePosition = function () {
  7784. this.computeWorldMatrix();
  7785. return this._absolutePosition;
  7786. };
  7787. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7788. if (!absolutePosition) {
  7789. return;
  7790. }
  7791. var absolutePositionX;
  7792. var absolutePositionY;
  7793. var absolutePositionZ;
  7794. if (absolutePosition.x === undefined) {
  7795. if (arguments.length < 3) {
  7796. return;
  7797. }
  7798. absolutePositionX = arguments[0];
  7799. absolutePositionY = arguments[1];
  7800. absolutePositionZ = arguments[2];
  7801. }
  7802. else {
  7803. absolutePositionX = absolutePosition.x;
  7804. absolutePositionY = absolutePosition.y;
  7805. absolutePositionZ = absolutePosition.z;
  7806. }
  7807. if (this.parent) {
  7808. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7809. invertParentWorldMatrix.invert();
  7810. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7811. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7812. }
  7813. else {
  7814. this.position.x = absolutePositionX;
  7815. this.position.y = absolutePositionY;
  7816. this.position.z = absolutePositionZ;
  7817. }
  7818. };
  7819. // ================================== Point of View Movement =================================
  7820. /**
  7821. * Perform relative position change from the point of view of behind the front of the mesh.
  7822. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7823. * Supports definition of mesh facing forward or backward.
  7824. * @param {number} amountRight
  7825. * @param {number} amountUp
  7826. * @param {number} amountForward
  7827. */
  7828. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7829. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7830. };
  7831. /**
  7832. * Calculate relative position change from the point of view of behind the front of the mesh.
  7833. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7834. * Supports definition of mesh facing forward or backward.
  7835. * @param {number} amountRight
  7836. * @param {number} amountUp
  7837. * @param {number} amountForward
  7838. */
  7839. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7840. var rotMatrix = new BABYLON.Matrix();
  7841. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7842. rotQuaternion.toRotationMatrix(rotMatrix);
  7843. var translationDelta = BABYLON.Vector3.Zero();
  7844. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7846. return translationDelta;
  7847. };
  7848. // ================================== Point of View Rotation =================================
  7849. /**
  7850. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7851. * Supports definition of mesh facing forward or backward.
  7852. * @param {number} flipBack
  7853. * @param {number} twirlClockwise
  7854. * @param {number} tiltRight
  7855. */
  7856. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7857. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7858. };
  7859. /**
  7860. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7861. * Supports definition of mesh facing forward or backward.
  7862. * @param {number} flipBack
  7863. * @param {number} twirlClockwise
  7864. * @param {number} tiltRight
  7865. */
  7866. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7867. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7868. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7869. };
  7870. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7871. this._pivotMatrix = matrix;
  7872. this._cache.pivotMatrixUpdated = true;
  7873. };
  7874. AbstractMesh.prototype.getPivotMatrix = function () {
  7875. return this._pivotMatrix;
  7876. };
  7877. AbstractMesh.prototype._isSynchronized = function () {
  7878. if (this._isDirty) {
  7879. return false;
  7880. }
  7881. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7882. return false;
  7883. if (this._cache.pivotMatrixUpdated) {
  7884. return false;
  7885. }
  7886. if (this.infiniteDistance) {
  7887. return false;
  7888. }
  7889. if (!this._cache.position.equals(this.position))
  7890. return false;
  7891. if (this.rotationQuaternion) {
  7892. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7893. return false;
  7894. }
  7895. else {
  7896. if (!this._cache.rotation.equals(this.rotation))
  7897. return false;
  7898. }
  7899. if (!this._cache.scaling.equals(this.scaling))
  7900. return false;
  7901. return true;
  7902. };
  7903. AbstractMesh.prototype._initCache = function () {
  7904. _super.prototype._initCache.call(this);
  7905. this._cache.localMatrixUpdated = false;
  7906. this._cache.position = BABYLON.Vector3.Zero();
  7907. this._cache.scaling = BABYLON.Vector3.Zero();
  7908. this._cache.rotation = BABYLON.Vector3.Zero();
  7909. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7910. this._cache.billboardMode = -1;
  7911. };
  7912. AbstractMesh.prototype.markAsDirty = function (property) {
  7913. if (property === "rotation") {
  7914. this.rotationQuaternion = null;
  7915. }
  7916. this._currentRenderId = Number.MAX_VALUE;
  7917. this._isDirty = true;
  7918. };
  7919. AbstractMesh.prototype._updateBoundingInfo = function () {
  7920. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7921. this._boundingInfo._update(this.worldMatrixFromCache);
  7922. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7923. };
  7924. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7925. if (!this.subMeshes) {
  7926. return;
  7927. }
  7928. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7929. var subMesh = this.subMeshes[subIndex];
  7930. subMesh.updateBoundingInfo(matrix);
  7931. }
  7932. };
  7933. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7934. if (this._isWorldMatrixFrozen) {
  7935. return this._worldMatrix;
  7936. }
  7937. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7938. return this._worldMatrix;
  7939. }
  7940. this._cache.position.copyFrom(this.position);
  7941. this._cache.scaling.copyFrom(this.scaling);
  7942. this._cache.pivotMatrixUpdated = false;
  7943. this._cache.billboardMode = this.billboardMode;
  7944. this._currentRenderId = this.getScene().getRenderId();
  7945. this._isDirty = false;
  7946. // Scaling
  7947. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7948. // Rotation
  7949. if (this.rotationQuaternion) {
  7950. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7951. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7952. }
  7953. else {
  7954. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7955. this._cache.rotation.copyFrom(this.rotation);
  7956. }
  7957. // Translation
  7958. if (this.infiniteDistance && !this.parent) {
  7959. var camera = this.getScene().activeCamera;
  7960. if (camera) {
  7961. var cameraWorldMatrix = camera.getWorldMatrix();
  7962. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7963. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7964. }
  7965. }
  7966. else {
  7967. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7968. }
  7969. // Composing transformations
  7970. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7971. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7972. // Billboarding
  7973. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7974. var localPosition = this.position.clone();
  7975. var zero = this.getScene().activeCamera.globalPosition.clone();
  7976. if (this.parent && this.parent.position) {
  7977. localPosition.addInPlace(this.parent.position);
  7978. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7979. }
  7980. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7981. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7982. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7983. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7984. zero.y = localPosition.y + 0.001;
  7985. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7986. zero.z = localPosition.z + 0.001;
  7987. }
  7988. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7989. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7990. this._localBillboard.invert();
  7991. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7992. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7993. }
  7994. // Local world
  7995. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7996. // Parent
  7997. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7998. this._markSyncedWithParent();
  7999. if (this._meshToBoneReferal) {
  8000. if (!this._localMeshReferalTransform) {
  8001. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8002. }
  8003. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8004. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8005. }
  8006. else {
  8007. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8008. }
  8009. }
  8010. else {
  8011. this._worldMatrix.copyFrom(this._localWorld);
  8012. }
  8013. // Bounding info
  8014. this._updateBoundingInfo();
  8015. // Absolute position
  8016. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8017. // Callbacks
  8018. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8019. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8020. }
  8021. return this._worldMatrix;
  8022. };
  8023. /**
  8024. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8025. * @param func: callback function to add
  8026. */
  8027. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8028. this._onAfterWorldMatrixUpdate.push(func);
  8029. };
  8030. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8031. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8032. if (index > -1) {
  8033. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8034. }
  8035. };
  8036. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8037. this.computeWorldMatrix();
  8038. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8039. };
  8040. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8041. this.computeWorldMatrix();
  8042. var invLocalWorldMatrix = this._localWorld.clone();
  8043. invLocalWorldMatrix.invert();
  8044. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8045. };
  8046. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8047. this.computeWorldMatrix(true);
  8048. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8049. };
  8050. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8051. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8052. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8053. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8054. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8055. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8056. /// <returns>Mesh oriented towards targetMesh</returns>
  8057. yawCor = yawCor || 0; // default to zero if undefined
  8058. pitchCor = pitchCor || 0;
  8059. rollCor = rollCor || 0;
  8060. var dv = targetPoint.subtract(this.position);
  8061. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8062. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8063. var pitch = Math.atan2(dv.y, len);
  8064. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8065. };
  8066. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8067. this._meshToBoneReferal = affectedMesh;
  8068. this.parent = bone;
  8069. if (bone.getWorldMatrix().determinant() < 0) {
  8070. this.scalingDeterminant *= -1;
  8071. }
  8072. };
  8073. AbstractMesh.prototype.detachFromBone = function () {
  8074. if (this.parent.getWorldMatrix().determinant() < 0) {
  8075. this.scalingDeterminant *= -1;
  8076. }
  8077. this._meshToBoneReferal = null;
  8078. this.parent = null;
  8079. };
  8080. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8081. return this._boundingInfo.isInFrustum(frustumPlanes);
  8082. };
  8083. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8084. if (!camera) {
  8085. camera = this.getScene().activeCamera;
  8086. }
  8087. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8088. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8089. return false;
  8090. }
  8091. return true;
  8092. };
  8093. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8094. if (!this._boundingInfo || !mesh._boundingInfo) {
  8095. return false;
  8096. }
  8097. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8098. };
  8099. AbstractMesh.prototype.intersectsPoint = function (point) {
  8100. if (!this._boundingInfo) {
  8101. return false;
  8102. }
  8103. return this._boundingInfo.intersectsPoint(point);
  8104. };
  8105. // Physics
  8106. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8107. var physicsEngine = this.getScene().getPhysicsEngine();
  8108. if (!physicsEngine) {
  8109. return null;
  8110. }
  8111. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8112. if (impostor.impostor) {
  8113. // Old API
  8114. options = impostor;
  8115. impostor = impostor.impostor;
  8116. }
  8117. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8118. physicsEngine._unregisterMesh(this);
  8119. return null;
  8120. }
  8121. if (!options) {
  8122. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8123. }
  8124. else {
  8125. if (!options.mass && options.mass !== 0)
  8126. options.mass = 0;
  8127. if (!options.friction && options.friction !== 0)
  8128. options.friction = 0.2;
  8129. if (!options.restitution && options.restitution !== 0)
  8130. options.restitution = 0.2;
  8131. }
  8132. this._physicImpostor = impostor;
  8133. this._physicsMass = options.mass;
  8134. this._physicsFriction = options.friction;
  8135. this._physicRestitution = options.restitution;
  8136. return physicsEngine._registerMesh(this, impostor, options);
  8137. };
  8138. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8139. if (!this._physicImpostor) {
  8140. return BABYLON.PhysicsEngine.NoImpostor;
  8141. }
  8142. return this._physicImpostor;
  8143. };
  8144. AbstractMesh.prototype.getPhysicsMass = function () {
  8145. if (!this._physicsMass) {
  8146. return 0;
  8147. }
  8148. return this._physicsMass;
  8149. };
  8150. AbstractMesh.prototype.getPhysicsFriction = function () {
  8151. if (!this._physicsFriction) {
  8152. return 0;
  8153. }
  8154. return this._physicsFriction;
  8155. };
  8156. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8157. if (!this._physicRestitution) {
  8158. return 0;
  8159. }
  8160. return this._physicRestitution;
  8161. };
  8162. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8163. if (!camera) {
  8164. camera = this.getScene().activeCamera;
  8165. }
  8166. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8167. };
  8168. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8169. if (!camera) {
  8170. camera = this.getScene().activeCamera;
  8171. }
  8172. return this.absolutePosition.subtract(camera.position).length();
  8173. };
  8174. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8175. if (!this._physicImpostor) {
  8176. return;
  8177. }
  8178. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8179. };
  8180. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8181. if (!this._physicImpostor) {
  8182. return;
  8183. }
  8184. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8185. };
  8186. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8187. if (!this._physicImpostor) {
  8188. return;
  8189. }
  8190. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8191. };
  8192. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8193. // Collisions
  8194. get: function () {
  8195. return this._checkCollisions;
  8196. },
  8197. set: function (collisionEnabled) {
  8198. this._checkCollisions = collisionEnabled;
  8199. if (this.getScene().workerCollisions) {
  8200. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8201. }
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8207. var globalPosition = this.getAbsolutePosition();
  8208. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8209. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8210. this._collider.radius = this.ellipsoid;
  8211. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8212. };
  8213. // Submeshes octree
  8214. /**
  8215. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8216. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8217. */
  8218. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8219. if (maxCapacity === void 0) { maxCapacity = 64; }
  8220. if (maxDepth === void 0) { maxDepth = 2; }
  8221. if (!this._submeshesOctree) {
  8222. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8223. }
  8224. this.computeWorldMatrix(true);
  8225. // Update octree
  8226. var bbox = this.getBoundingInfo().boundingBox;
  8227. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8228. return this._submeshesOctree;
  8229. };
  8230. // Collisions
  8231. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8232. this._generatePointsArray();
  8233. // Transformation
  8234. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8235. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8236. subMesh._lastColliderWorldVertices = [];
  8237. subMesh._trianglePlanes = [];
  8238. var start = subMesh.verticesStart;
  8239. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8240. for (var i = start; i < end; i++) {
  8241. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8242. }
  8243. }
  8244. // Collide
  8245. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8246. if (collider.collisionFound) {
  8247. collider.collidedMesh = this;
  8248. }
  8249. };
  8250. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8251. var subMeshes;
  8252. var len;
  8253. // Octrees
  8254. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8255. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8256. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8257. len = intersections.length;
  8258. subMeshes = intersections.data;
  8259. }
  8260. else {
  8261. subMeshes = this.subMeshes;
  8262. len = subMeshes.length;
  8263. }
  8264. for (var index = 0; index < len; index++) {
  8265. var subMesh = subMeshes[index];
  8266. // Bounding test
  8267. if (len > 1 && !subMesh._checkCollision(collider))
  8268. continue;
  8269. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8270. }
  8271. };
  8272. AbstractMesh.prototype._checkCollision = function (collider) {
  8273. // Bounding box test
  8274. if (!this._boundingInfo._checkCollision(collider))
  8275. return;
  8276. // Transformation matrix
  8277. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8278. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8279. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8280. };
  8281. // Picking
  8282. AbstractMesh.prototype._generatePointsArray = function () {
  8283. return false;
  8284. };
  8285. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8286. var pickingInfo = new BABYLON.PickingInfo();
  8287. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8288. return pickingInfo;
  8289. }
  8290. if (!this._generatePointsArray()) {
  8291. return pickingInfo;
  8292. }
  8293. var intersectInfo = null;
  8294. // Octrees
  8295. var subMeshes;
  8296. var len;
  8297. if (this._submeshesOctree && this.useOctreeForPicking) {
  8298. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8299. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8300. len = intersections.length;
  8301. subMeshes = intersections.data;
  8302. }
  8303. else {
  8304. subMeshes = this.subMeshes;
  8305. len = subMeshes.length;
  8306. }
  8307. for (var index = 0; index < len; index++) {
  8308. var subMesh = subMeshes[index];
  8309. // Bounding test
  8310. if (len > 1 && !subMesh.canIntersects(ray))
  8311. continue;
  8312. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8313. if (currentIntersectInfo) {
  8314. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8315. intersectInfo = currentIntersectInfo;
  8316. intersectInfo.subMeshId = index;
  8317. if (fastCheck) {
  8318. break;
  8319. }
  8320. }
  8321. }
  8322. }
  8323. if (intersectInfo) {
  8324. // Get picked point
  8325. var world = this.getWorldMatrix();
  8326. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8327. var direction = ray.direction.clone();
  8328. direction = direction.scale(intersectInfo.distance);
  8329. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8330. var pickedPoint = worldOrigin.add(worldDirection);
  8331. // Return result
  8332. pickingInfo.hit = true;
  8333. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8334. pickingInfo.pickedPoint = pickedPoint;
  8335. pickingInfo.pickedMesh = this;
  8336. pickingInfo.bu = intersectInfo.bu;
  8337. pickingInfo.bv = intersectInfo.bv;
  8338. pickingInfo.faceId = intersectInfo.faceId;
  8339. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8340. return pickingInfo;
  8341. }
  8342. return pickingInfo;
  8343. };
  8344. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8345. return null;
  8346. };
  8347. AbstractMesh.prototype.releaseSubMeshes = function () {
  8348. if (this.subMeshes) {
  8349. while (this.subMeshes.length) {
  8350. this.subMeshes[0].dispose();
  8351. }
  8352. }
  8353. else {
  8354. this.subMeshes = new Array();
  8355. }
  8356. };
  8357. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8358. var index;
  8359. // Animations
  8360. this.getScene().stopAnimation(this);
  8361. // Physics
  8362. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8363. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8364. }
  8365. // Intersections in progress
  8366. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8367. var other = this._intersectionsInProgress[index];
  8368. var pos = other._intersectionsInProgress.indexOf(this);
  8369. other._intersectionsInProgress.splice(pos, 1);
  8370. }
  8371. this._intersectionsInProgress = [];
  8372. // Edges
  8373. if (this._edgesRenderer) {
  8374. this._edgesRenderer.dispose();
  8375. this._edgesRenderer = null;
  8376. }
  8377. // SubMeshes
  8378. this.releaseSubMeshes();
  8379. // Remove from scene
  8380. this.getScene().removeMesh(this);
  8381. if (!doNotRecurse) {
  8382. // Particles
  8383. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8384. if (this.getScene().particleSystems[index].emitter === this) {
  8385. this.getScene().particleSystems[index].dispose();
  8386. index--;
  8387. }
  8388. }
  8389. // Children
  8390. var objects = this.getScene().meshes.slice(0);
  8391. for (index = 0; index < objects.length; index++) {
  8392. if (objects[index].parent === this) {
  8393. objects[index].dispose();
  8394. }
  8395. }
  8396. }
  8397. else {
  8398. for (index = 0; index < this.getScene().meshes.length; index++) {
  8399. var obj = this.getScene().meshes[index];
  8400. if (obj.parent === this) {
  8401. obj.parent = null;
  8402. obj.computeWorldMatrix(true);
  8403. }
  8404. }
  8405. }
  8406. this._onAfterWorldMatrixUpdate = [];
  8407. this._isDisposed = true;
  8408. // Callback
  8409. if (this.onDispose) {
  8410. this.onDispose();
  8411. }
  8412. };
  8413. // Statics
  8414. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8415. AbstractMesh._BILLBOARDMODE_X = 1;
  8416. AbstractMesh._BILLBOARDMODE_Y = 2;
  8417. AbstractMesh._BILLBOARDMODE_Z = 4;
  8418. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8419. return AbstractMesh;
  8420. })(BABYLON.Node);
  8421. BABYLON.AbstractMesh = AbstractMesh;
  8422. })(BABYLON || (BABYLON = {}));
  8423. var BABYLON;
  8424. (function (BABYLON) {
  8425. var Light = (function (_super) {
  8426. __extends(Light, _super);
  8427. function Light(name, scene) {
  8428. _super.call(this, name, scene);
  8429. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8430. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8431. this.intensity = 1.0;
  8432. this.range = Number.MAX_VALUE;
  8433. this.includeOnlyWithLayerMask = 0;
  8434. this.includedOnlyMeshes = new Array();
  8435. this.excludedMeshes = new Array();
  8436. this.excludeWithLayerMask = 0;
  8437. this._excludedMeshesIds = new Array();
  8438. this._includedOnlyMeshesIds = new Array();
  8439. scene.addLight(this);
  8440. }
  8441. Light.prototype.getShadowGenerator = function () {
  8442. return this._shadowGenerator;
  8443. };
  8444. Light.prototype.getAbsolutePosition = function () {
  8445. return BABYLON.Vector3.Zero();
  8446. };
  8447. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8448. };
  8449. Light.prototype._getWorldMatrix = function () {
  8450. return BABYLON.Matrix.Identity();
  8451. };
  8452. Light.prototype.canAffectMesh = function (mesh) {
  8453. if (!mesh) {
  8454. return true;
  8455. }
  8456. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8457. return false;
  8458. }
  8459. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8460. return false;
  8461. }
  8462. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8463. return false;
  8464. }
  8465. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8466. return false;
  8467. }
  8468. return true;
  8469. };
  8470. Light.prototype.getWorldMatrix = function () {
  8471. this._currentRenderId = this.getScene().getRenderId();
  8472. var worldMatrix = this._getWorldMatrix();
  8473. if (this.parent && this.parent.getWorldMatrix) {
  8474. if (!this._parentedWorldMatrix) {
  8475. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8476. }
  8477. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8478. this._markSyncedWithParent();
  8479. return this._parentedWorldMatrix;
  8480. }
  8481. return worldMatrix;
  8482. };
  8483. Light.prototype.dispose = function () {
  8484. if (this._shadowGenerator) {
  8485. this._shadowGenerator.dispose();
  8486. this._shadowGenerator = null;
  8487. }
  8488. // Animations
  8489. this.getScene().stopAnimation(this);
  8490. // Remove from scene
  8491. this.getScene().removeLight(this);
  8492. };
  8493. Light.prototype.serialize = function () {
  8494. var serializationObject = {};
  8495. serializationObject.name = this.name;
  8496. serializationObject.id = this.id;
  8497. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8498. if (this.intensity) {
  8499. serializationObject.intensity = this.intensity;
  8500. }
  8501. serializationObject.range = this.range;
  8502. serializationObject.diffuse = this.diffuse.asArray();
  8503. serializationObject.specular = this.specular.asArray();
  8504. return serializationObject;
  8505. };
  8506. Light.Parse = function (parsedLight, scene) {
  8507. var light;
  8508. switch (parsedLight.type) {
  8509. case 0:
  8510. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8511. break;
  8512. case 1:
  8513. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8514. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8515. break;
  8516. case 2:
  8517. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8518. break;
  8519. case 3:
  8520. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8521. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8522. break;
  8523. }
  8524. light.id = parsedLight.id;
  8525. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8526. if (parsedLight.intensity !== undefined) {
  8527. light.intensity = parsedLight.intensity;
  8528. }
  8529. if (parsedLight.range) {
  8530. light.range = parsedLight.range;
  8531. }
  8532. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8533. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8534. if (parsedLight.excludedMeshesIds) {
  8535. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8536. }
  8537. // Parent
  8538. if (parsedLight.parentId) {
  8539. light._waitingParentId = parsedLight.parentId;
  8540. }
  8541. if (parsedLight.includedOnlyMeshesIds) {
  8542. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8543. }
  8544. // Animations
  8545. if (parsedLight.animations) {
  8546. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8547. var parsedAnimation = parsedLight.animations[animationIndex];
  8548. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8549. }
  8550. }
  8551. if (parsedLight.autoAnimate) {
  8552. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8553. }
  8554. return light;
  8555. };
  8556. return Light;
  8557. })(BABYLON.Node);
  8558. BABYLON.Light = Light;
  8559. })(BABYLON || (BABYLON = {}));
  8560. var BABYLON;
  8561. (function (BABYLON) {
  8562. var PointLight = (function (_super) {
  8563. __extends(PointLight, _super);
  8564. function PointLight(name, position, scene) {
  8565. _super.call(this, name, scene);
  8566. this.position = position;
  8567. }
  8568. PointLight.prototype.getAbsolutePosition = function () {
  8569. return this.transformedPosition ? this.transformedPosition : this.position;
  8570. };
  8571. PointLight.prototype.computeTransformedPosition = function () {
  8572. if (this.parent && this.parent.getWorldMatrix) {
  8573. if (!this.transformedPosition) {
  8574. this.transformedPosition = BABYLON.Vector3.Zero();
  8575. }
  8576. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8577. return true;
  8578. }
  8579. return false;
  8580. };
  8581. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8582. if (this.parent && this.parent.getWorldMatrix) {
  8583. this.computeTransformedPosition();
  8584. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8585. return;
  8586. }
  8587. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8588. };
  8589. PointLight.prototype.needCube = function () {
  8590. return true;
  8591. };
  8592. PointLight.prototype.supportsVSM = function () {
  8593. return false;
  8594. };
  8595. PointLight.prototype.needRefreshPerFrame = function () {
  8596. return false;
  8597. };
  8598. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8599. switch (faceIndex) {
  8600. case 0:
  8601. return new BABYLON.Vector3(1, 0, 0);
  8602. case 1:
  8603. return new BABYLON.Vector3(-1, 0, 0);
  8604. case 2:
  8605. return new BABYLON.Vector3(0, -1, 0);
  8606. case 3:
  8607. return new BABYLON.Vector3(0, 1, 0);
  8608. case 4:
  8609. return new BABYLON.Vector3(0, 0, 1);
  8610. case 5:
  8611. return new BABYLON.Vector3(0, 0, -1);
  8612. }
  8613. return BABYLON.Vector3.Zero();
  8614. };
  8615. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8616. var activeCamera = this.getScene().activeCamera;
  8617. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8618. };
  8619. PointLight.prototype._getWorldMatrix = function () {
  8620. if (!this._worldMatrix) {
  8621. this._worldMatrix = BABYLON.Matrix.Identity();
  8622. }
  8623. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8624. return this._worldMatrix;
  8625. };
  8626. PointLight.prototype.serialize = function () {
  8627. var serializationObject = _super.prototype.serialize.call(this);
  8628. serializationObject.type = 0;
  8629. serializationObject.position = this.position.asArray();
  8630. return serializationObject;
  8631. };
  8632. return PointLight;
  8633. })(BABYLON.Light);
  8634. BABYLON.PointLight = PointLight;
  8635. })(BABYLON || (BABYLON = {}));
  8636. var BABYLON;
  8637. (function (BABYLON) {
  8638. var SpotLight = (function (_super) {
  8639. __extends(SpotLight, _super);
  8640. function SpotLight(name, position, direction, angle, exponent, scene) {
  8641. _super.call(this, name, scene);
  8642. this.position = position;
  8643. this.direction = direction;
  8644. this.angle = angle;
  8645. this.exponent = exponent;
  8646. }
  8647. SpotLight.prototype.getAbsolutePosition = function () {
  8648. return this.transformedPosition ? this.transformedPosition : this.position;
  8649. };
  8650. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8651. var activeCamera = this.getScene().activeCamera;
  8652. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8653. };
  8654. SpotLight.prototype.needCube = function () {
  8655. return false;
  8656. };
  8657. SpotLight.prototype.supportsVSM = function () {
  8658. return true;
  8659. };
  8660. SpotLight.prototype.needRefreshPerFrame = function () {
  8661. return false;
  8662. };
  8663. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8664. return this.direction;
  8665. };
  8666. SpotLight.prototype.setDirectionToTarget = function (target) {
  8667. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8668. return this.direction;
  8669. };
  8670. SpotLight.prototype.computeTransformedPosition = function () {
  8671. if (this.parent && this.parent.getWorldMatrix) {
  8672. if (!this.transformedPosition) {
  8673. this.transformedPosition = BABYLON.Vector3.Zero();
  8674. }
  8675. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8676. return true;
  8677. }
  8678. return false;
  8679. };
  8680. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8681. var normalizeDirection;
  8682. if (this.parent && this.parent.getWorldMatrix) {
  8683. if (!this._transformedDirection) {
  8684. this._transformedDirection = BABYLON.Vector3.Zero();
  8685. }
  8686. this.computeTransformedPosition();
  8687. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8688. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8689. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8690. }
  8691. else {
  8692. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8693. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8694. }
  8695. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8696. };
  8697. SpotLight.prototype._getWorldMatrix = function () {
  8698. if (!this._worldMatrix) {
  8699. this._worldMatrix = BABYLON.Matrix.Identity();
  8700. }
  8701. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8702. return this._worldMatrix;
  8703. };
  8704. SpotLight.prototype.serialize = function () {
  8705. var serializationObject = _super.prototype.serialize.call(this);
  8706. serializationObject.type = 2;
  8707. serializationObject.position = this.position.asArray();
  8708. serializationObject.direction = this.position.asArray();
  8709. serializationObject.angle = this.angle;
  8710. serializationObject.exponent = this.exponent;
  8711. return serializationObject;
  8712. };
  8713. return SpotLight;
  8714. })(BABYLON.Light);
  8715. BABYLON.SpotLight = SpotLight;
  8716. })(BABYLON || (BABYLON = {}));
  8717. var BABYLON;
  8718. (function (BABYLON) {
  8719. var HemisphericLight = (function (_super) {
  8720. __extends(HemisphericLight, _super);
  8721. function HemisphericLight(name, direction, scene) {
  8722. _super.call(this, name, scene);
  8723. this.direction = direction;
  8724. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8725. }
  8726. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8727. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8728. return this.direction;
  8729. };
  8730. HemisphericLight.prototype.getShadowGenerator = function () {
  8731. return null;
  8732. };
  8733. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8734. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8735. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8736. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8737. };
  8738. HemisphericLight.prototype._getWorldMatrix = function () {
  8739. if (!this._worldMatrix) {
  8740. this._worldMatrix = BABYLON.Matrix.Identity();
  8741. }
  8742. return this._worldMatrix;
  8743. };
  8744. HemisphericLight.prototype.serialize = function () {
  8745. var serializationObject = _super.prototype.serialize.call(this);
  8746. serializationObject.type = 3;
  8747. serializationObject.direction = this.direction.asArray();
  8748. serializationObject.groundColor = this.groundColor.asArray();
  8749. return serializationObject;
  8750. };
  8751. return HemisphericLight;
  8752. })(BABYLON.Light);
  8753. BABYLON.HemisphericLight = HemisphericLight;
  8754. })(BABYLON || (BABYLON = {}));
  8755. var BABYLON;
  8756. (function (BABYLON) {
  8757. var DirectionalLight = (function (_super) {
  8758. __extends(DirectionalLight, _super);
  8759. function DirectionalLight(name, direction, scene) {
  8760. _super.call(this, name, scene);
  8761. this.direction = direction;
  8762. this.shadowOrthoScale = 0.5;
  8763. this.autoUpdateExtends = true;
  8764. // Cache
  8765. this._orthoLeft = Number.MAX_VALUE;
  8766. this._orthoRight = Number.MIN_VALUE;
  8767. this._orthoTop = Number.MIN_VALUE;
  8768. this._orthoBottom = Number.MAX_VALUE;
  8769. this.position = direction.scale(-1);
  8770. }
  8771. DirectionalLight.prototype.getAbsolutePosition = function () {
  8772. return this.transformedPosition ? this.transformedPosition : this.position;
  8773. };
  8774. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8775. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8776. return this.direction;
  8777. };
  8778. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8779. var activeCamera = this.getScene().activeCamera;
  8780. // Check extends
  8781. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8782. var tempVector3 = BABYLON.Vector3.Zero();
  8783. this._orthoLeft = Number.MAX_VALUE;
  8784. this._orthoRight = Number.MIN_VALUE;
  8785. this._orthoTop = Number.MIN_VALUE;
  8786. this._orthoBottom = Number.MAX_VALUE;
  8787. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8788. var mesh = renderList[meshIndex];
  8789. if (!mesh) {
  8790. continue;
  8791. }
  8792. var boundingInfo = mesh.getBoundingInfo();
  8793. if (!boundingInfo) {
  8794. continue;
  8795. }
  8796. var boundingBox = boundingInfo.boundingBox;
  8797. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8798. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8799. if (tempVector3.x < this._orthoLeft)
  8800. this._orthoLeft = tempVector3.x;
  8801. if (tempVector3.y < this._orthoBottom)
  8802. this._orthoBottom = tempVector3.y;
  8803. if (tempVector3.x > this._orthoRight)
  8804. this._orthoRight = tempVector3.x;
  8805. if (tempVector3.y > this._orthoTop)
  8806. this._orthoTop = tempVector3.y;
  8807. }
  8808. }
  8809. }
  8810. var xOffset = this._orthoRight - this._orthoLeft;
  8811. var yOffset = this._orthoTop - this._orthoBottom;
  8812. 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);
  8813. };
  8814. DirectionalLight.prototype.supportsVSM = function () {
  8815. return true;
  8816. };
  8817. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8818. return true;
  8819. };
  8820. DirectionalLight.prototype.needCube = function () {
  8821. return false;
  8822. };
  8823. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8824. return this.direction;
  8825. };
  8826. DirectionalLight.prototype.computeTransformedPosition = function () {
  8827. if (this.parent && this.parent.getWorldMatrix) {
  8828. if (!this.transformedPosition) {
  8829. this.transformedPosition = BABYLON.Vector3.Zero();
  8830. }
  8831. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8832. return true;
  8833. }
  8834. return false;
  8835. };
  8836. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8837. if (this.parent && this.parent.getWorldMatrix) {
  8838. if (!this._transformedDirection) {
  8839. this._transformedDirection = BABYLON.Vector3.Zero();
  8840. }
  8841. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8842. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8843. return;
  8844. }
  8845. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8846. };
  8847. DirectionalLight.prototype._getWorldMatrix = function () {
  8848. if (!this._worldMatrix) {
  8849. this._worldMatrix = BABYLON.Matrix.Identity();
  8850. }
  8851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8852. return this._worldMatrix;
  8853. };
  8854. DirectionalLight.prototype.serialize = function () {
  8855. var serializationObject = _super.prototype.serialize.call(this);
  8856. serializationObject.type = 1;
  8857. serializationObject.position = this.position.asArray();
  8858. serializationObject.direction = this.direction.asArray();
  8859. return serializationObject;
  8860. };
  8861. return DirectionalLight;
  8862. })(BABYLON.Light);
  8863. BABYLON.DirectionalLight = DirectionalLight;
  8864. })(BABYLON || (BABYLON = {}));
  8865. var BABYLON;
  8866. (function (BABYLON) {
  8867. var ShadowGenerator = (function () {
  8868. function ShadowGenerator(mapSize, light) {
  8869. var _this = this;
  8870. // Members
  8871. this._filter = ShadowGenerator.FILTER_NONE;
  8872. this.blurScale = 2;
  8873. this._blurBoxOffset = 0;
  8874. this._bias = 0.00005;
  8875. this._lightDirection = BABYLON.Vector3.Zero();
  8876. this._darkness = 0;
  8877. this._transparencyShadow = false;
  8878. this._viewMatrix = BABYLON.Matrix.Zero();
  8879. this._projectionMatrix = BABYLON.Matrix.Zero();
  8880. this._transformMatrix = BABYLON.Matrix.Zero();
  8881. this._worldViewProjection = BABYLON.Matrix.Zero();
  8882. this._currentFaceIndex = 0;
  8883. this._currentFaceIndexCache = 0;
  8884. this._light = light;
  8885. this._scene = light.getScene();
  8886. this._mapSize = mapSize;
  8887. light._shadowGenerator = this;
  8888. // Render target
  8889. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8890. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8891. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8892. this._shadowMap.anisotropicFilteringLevel = 1;
  8893. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8894. this._shadowMap.renderParticles = false;
  8895. this._shadowMap.onBeforeRender = function (faceIndex) {
  8896. _this._currentFaceIndex = faceIndex;
  8897. };
  8898. this._shadowMap.onAfterUnbind = function () {
  8899. if (!_this.useBlurVarianceShadowMap) {
  8900. return;
  8901. }
  8902. if (!_this._shadowMap2) {
  8903. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8904. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8905. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8906. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8907. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8908. _this._downSamplePostprocess.onApply = function (effect) {
  8909. effect.setTexture("textureSampler", _this._shadowMap);
  8910. };
  8911. _this.blurBoxOffset = 1;
  8912. }
  8913. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8914. };
  8915. // Custom render function
  8916. var renderSubMesh = function (subMesh) {
  8917. var mesh = subMesh.getRenderingMesh();
  8918. var scene = _this._scene;
  8919. var engine = scene.getEngine();
  8920. // Culling
  8921. engine.setState(subMesh.getMaterial().backFaceCulling);
  8922. // Managing instances
  8923. var batch = mesh._getInstancesRenderList(subMesh._id);
  8924. if (batch.mustReturn) {
  8925. return;
  8926. }
  8927. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8928. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8929. engine.enableEffect(_this._effect);
  8930. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8931. var material = subMesh.getMaterial();
  8932. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8933. // Alpha test
  8934. if (material && material.needAlphaTesting()) {
  8935. var alphaTexture = material.getAlphaTestTexture();
  8936. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8937. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8938. }
  8939. // Bones
  8940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8941. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8942. }
  8943. // Draw
  8944. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8945. }
  8946. else {
  8947. // Need to reset refresh rate of the shadowMap
  8948. _this._shadowMap.resetRefreshCounter();
  8949. }
  8950. };
  8951. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8952. var index;
  8953. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8954. renderSubMesh(opaqueSubMeshes.data[index]);
  8955. }
  8956. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8957. renderSubMesh(alphaTestSubMeshes.data[index]);
  8958. }
  8959. if (_this._transparencyShadow) {
  8960. for (index = 0; index < transparentSubMeshes.length; index++) {
  8961. renderSubMesh(transparentSubMeshes.data[index]);
  8962. }
  8963. }
  8964. };
  8965. this._shadowMap.onClear = function (engine) {
  8966. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8967. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8968. }
  8969. else {
  8970. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8971. }
  8972. };
  8973. }
  8974. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8975. // Static
  8976. get: function () {
  8977. return ShadowGenerator._FILTER_NONE;
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8983. get: function () {
  8984. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8985. },
  8986. enumerable: true,
  8987. configurable: true
  8988. });
  8989. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8990. get: function () {
  8991. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8992. },
  8993. enumerable: true,
  8994. configurable: true
  8995. });
  8996. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8997. get: function () {
  8998. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8999. },
  9000. enumerable: true,
  9001. configurable: true
  9002. });
  9003. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9004. get: function () {
  9005. return this._bias;
  9006. },
  9007. set: function (bias) {
  9008. this._bias = bias;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9014. get: function () {
  9015. return this._blurBoxOffset;
  9016. },
  9017. set: function (value) {
  9018. var _this = this;
  9019. if (this._blurBoxOffset === value) {
  9020. return;
  9021. }
  9022. this._blurBoxOffset = value;
  9023. if (this._boxBlurPostprocess) {
  9024. this._boxBlurPostprocess.dispose();
  9025. }
  9026. 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);
  9027. this._boxBlurPostprocess.onApply = function (effect) {
  9028. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9029. };
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9035. get: function () {
  9036. return this._filter;
  9037. },
  9038. set: function (value) {
  9039. if (this._filter === value) {
  9040. return;
  9041. }
  9042. this._filter = value;
  9043. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9044. this._shadowMap.anisotropicFilteringLevel = 16;
  9045. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9046. }
  9047. else {
  9048. this._shadowMap.anisotropicFilteringLevel = 1;
  9049. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9050. }
  9051. },
  9052. enumerable: true,
  9053. configurable: true
  9054. });
  9055. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9056. get: function () {
  9057. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9058. },
  9059. set: function (value) {
  9060. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9066. get: function () {
  9067. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9068. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9069. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9070. },
  9071. set: function (value) {
  9072. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9078. get: function () {
  9079. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9080. },
  9081. set: function (value) {
  9082. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9088. var defines = [];
  9089. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9090. defines.push("#define VSM");
  9091. }
  9092. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9093. var mesh = subMesh.getMesh();
  9094. var material = subMesh.getMaterial();
  9095. // Alpha test
  9096. if (material && material.needAlphaTesting()) {
  9097. defines.push("#define ALPHATEST");
  9098. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9099. attribs.push(BABYLON.VertexBuffer.UVKind);
  9100. defines.push("#define UV1");
  9101. }
  9102. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9103. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9104. defines.push("#define UV2");
  9105. }
  9106. }
  9107. // Bones
  9108. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9109. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9110. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9111. if (mesh.numBoneInfluencers > 4) {
  9112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9114. }
  9115. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9116. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9117. }
  9118. else {
  9119. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9120. }
  9121. // Instances
  9122. if (useInstances) {
  9123. defines.push("#define INSTANCES");
  9124. attribs.push("world0");
  9125. attribs.push("world1");
  9126. attribs.push("world2");
  9127. attribs.push("world3");
  9128. }
  9129. // Get correct effect
  9130. var join = defines.join("\n");
  9131. if (this._cachedDefines !== join) {
  9132. this._cachedDefines = join;
  9133. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9134. }
  9135. return this._effect.isReady();
  9136. };
  9137. ShadowGenerator.prototype.getShadowMap = function () {
  9138. return this._shadowMap;
  9139. };
  9140. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9141. if (this._shadowMap2) {
  9142. return this._shadowMap2;
  9143. }
  9144. return this._shadowMap;
  9145. };
  9146. ShadowGenerator.prototype.getLight = function () {
  9147. return this._light;
  9148. };
  9149. // Methods
  9150. ShadowGenerator.prototype.getTransformMatrix = function () {
  9151. var scene = this._scene;
  9152. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9153. return this._transformMatrix;
  9154. }
  9155. this._currentRenderID = scene.getRenderId();
  9156. this._currentFaceIndexCache = this._currentFaceIndex;
  9157. var lightPosition = this._light.position;
  9158. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9159. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9160. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9161. }
  9162. if (this._light.computeTransformedPosition()) {
  9163. lightPosition = this._light.transformedPosition;
  9164. }
  9165. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9166. this._cachedPosition = lightPosition.clone();
  9167. this._cachedDirection = this._lightDirection.clone();
  9168. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9169. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9170. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9171. }
  9172. return this._transformMatrix;
  9173. };
  9174. ShadowGenerator.prototype.getDarkness = function () {
  9175. return this._darkness;
  9176. };
  9177. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9178. if (darkness >= 1.0)
  9179. this._darkness = 1.0;
  9180. else if (darkness <= 0.0)
  9181. this._darkness = 0.0;
  9182. else
  9183. this._darkness = darkness;
  9184. };
  9185. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9186. this._transparencyShadow = hasShadow;
  9187. };
  9188. ShadowGenerator.prototype._packHalf = function (depth) {
  9189. var scale = depth * 255.0;
  9190. var fract = scale - Math.floor(scale);
  9191. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9192. };
  9193. ShadowGenerator.prototype.dispose = function () {
  9194. this._shadowMap.dispose();
  9195. if (this._shadowMap2) {
  9196. this._shadowMap2.dispose();
  9197. }
  9198. if (this._downSamplePostprocess) {
  9199. this._downSamplePostprocess.dispose();
  9200. }
  9201. if (this._boxBlurPostprocess) {
  9202. this._boxBlurPostprocess.dispose();
  9203. }
  9204. };
  9205. ShadowGenerator.prototype.serialize = function () {
  9206. var serializationObject = {};
  9207. serializationObject.lightId = this._light.id;
  9208. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9209. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9210. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9211. serializationObject.renderList = [];
  9212. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9213. var mesh = this.getShadowMap().renderList[meshIndex];
  9214. serializationObject.renderList.push(mesh.id);
  9215. }
  9216. return serializationObject;
  9217. };
  9218. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9219. //casting to point light, as light is missing the position attr and typescript complains.
  9220. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9221. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9222. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9223. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9224. shadowGenerator.getShadowMap().renderList.push(mesh);
  9225. }
  9226. if (parsedShadowGenerator.usePoissonSampling) {
  9227. shadowGenerator.usePoissonSampling = true;
  9228. }
  9229. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9230. shadowGenerator.useVarianceShadowMap = true;
  9231. }
  9232. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9233. shadowGenerator.useBlurVarianceShadowMap = true;
  9234. if (parsedShadowGenerator.blurScale) {
  9235. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9236. }
  9237. if (parsedShadowGenerator.blurBoxOffset) {
  9238. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9239. }
  9240. }
  9241. if (parsedShadowGenerator.bias !== undefined) {
  9242. shadowGenerator.bias = parsedShadowGenerator.bias;
  9243. }
  9244. return shadowGenerator;
  9245. };
  9246. ShadowGenerator._FILTER_NONE = 0;
  9247. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9248. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9249. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9250. return ShadowGenerator;
  9251. })();
  9252. BABYLON.ShadowGenerator = ShadowGenerator;
  9253. })(BABYLON || (BABYLON = {}));
  9254. var BABYLON;
  9255. (function (BABYLON) {
  9256. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9257. if (boxMin.x > sphereCenter.x + sphereRadius)
  9258. return false;
  9259. if (sphereCenter.x - sphereRadius > boxMax.x)
  9260. return false;
  9261. if (boxMin.y > sphereCenter.y + sphereRadius)
  9262. return false;
  9263. if (sphereCenter.y - sphereRadius > boxMax.y)
  9264. return false;
  9265. if (boxMin.z > sphereCenter.z + sphereRadius)
  9266. return false;
  9267. if (sphereCenter.z - sphereRadius > boxMax.z)
  9268. return false;
  9269. return true;
  9270. };
  9271. var getLowestRoot = function (a, b, c, maxR) {
  9272. var determinant = b * b - 4.0 * a * c;
  9273. var result = { root: 0, found: false };
  9274. if (determinant < 0)
  9275. return result;
  9276. var sqrtD = Math.sqrt(determinant);
  9277. var r1 = (-b - sqrtD) / (2.0 * a);
  9278. var r2 = (-b + sqrtD) / (2.0 * a);
  9279. if (r1 > r2) {
  9280. var temp = r2;
  9281. r2 = r1;
  9282. r1 = temp;
  9283. }
  9284. if (r1 > 0 && r1 < maxR) {
  9285. result.root = r1;
  9286. result.found = true;
  9287. return result;
  9288. }
  9289. if (r2 > 0 && r2 < maxR) {
  9290. result.root = r2;
  9291. result.found = true;
  9292. return result;
  9293. }
  9294. return result;
  9295. };
  9296. var Collider = (function () {
  9297. function Collider() {
  9298. this.radius = new BABYLON.Vector3(1, 1, 1);
  9299. this.retry = 0;
  9300. this.basePointWorld = BABYLON.Vector3.Zero();
  9301. this.velocityWorld = BABYLON.Vector3.Zero();
  9302. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9303. this._collisionPoint = BABYLON.Vector3.Zero();
  9304. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9305. this._tempVector = BABYLON.Vector3.Zero();
  9306. this._tempVector2 = BABYLON.Vector3.Zero();
  9307. this._tempVector3 = BABYLON.Vector3.Zero();
  9308. this._tempVector4 = BABYLON.Vector3.Zero();
  9309. this._edge = BABYLON.Vector3.Zero();
  9310. this._baseToVertex = BABYLON.Vector3.Zero();
  9311. this._destinationPoint = BABYLON.Vector3.Zero();
  9312. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9313. this._displacementVector = BABYLON.Vector3.Zero();
  9314. }
  9315. // Methods
  9316. Collider.prototype._initialize = function (source, dir, e) {
  9317. this.velocity = dir;
  9318. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9319. this.basePoint = source;
  9320. source.multiplyToRef(this.radius, this.basePointWorld);
  9321. dir.multiplyToRef(this.radius, this.velocityWorld);
  9322. this.velocityWorldLength = this.velocityWorld.length();
  9323. this.epsilon = e;
  9324. this.collisionFound = false;
  9325. };
  9326. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9327. pa.subtractToRef(point, this._tempVector);
  9328. pb.subtractToRef(point, this._tempVector2);
  9329. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9330. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9331. if (d < 0)
  9332. return false;
  9333. pc.subtractToRef(point, this._tempVector3);
  9334. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9335. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9336. if (d < 0)
  9337. return false;
  9338. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9339. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9340. return d >= 0;
  9341. };
  9342. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9343. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9344. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9345. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9346. return false;
  9347. }
  9348. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9349. return false;
  9350. return true;
  9351. };
  9352. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9353. var t0;
  9354. var embeddedInPlane = false;
  9355. //defensive programming, actually not needed.
  9356. if (!trianglePlaneArray) {
  9357. trianglePlaneArray = [];
  9358. }
  9359. if (!trianglePlaneArray[faceIndex]) {
  9360. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9361. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9362. }
  9363. var trianglePlane = trianglePlaneArray[faceIndex];
  9364. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9365. return;
  9366. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9367. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9368. if (normalDotVelocity == 0) {
  9369. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9370. return;
  9371. embeddedInPlane = true;
  9372. t0 = 0;
  9373. }
  9374. else {
  9375. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9376. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9377. if (t0 > t1) {
  9378. var temp = t1;
  9379. t1 = t0;
  9380. t0 = temp;
  9381. }
  9382. if (t0 > 1.0 || t1 < 0.0)
  9383. return;
  9384. if (t0 < 0)
  9385. t0 = 0;
  9386. if (t0 > 1.0)
  9387. t0 = 1.0;
  9388. }
  9389. this._collisionPoint.copyFromFloats(0, 0, 0);
  9390. var found = false;
  9391. var t = 1.0;
  9392. if (!embeddedInPlane) {
  9393. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9394. this.velocity.scaleToRef(t0, this._tempVector);
  9395. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9396. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9397. found = true;
  9398. t = t0;
  9399. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9400. }
  9401. }
  9402. if (!found) {
  9403. var velocitySquaredLength = this.velocity.lengthSquared();
  9404. var a = velocitySquaredLength;
  9405. this.basePoint.subtractToRef(p1, this._tempVector);
  9406. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9407. var c = this._tempVector.lengthSquared() - 1.0;
  9408. var lowestRoot = getLowestRoot(a, b, c, t);
  9409. if (lowestRoot.found) {
  9410. t = lowestRoot.root;
  9411. found = true;
  9412. this._collisionPoint.copyFrom(p1);
  9413. }
  9414. this.basePoint.subtractToRef(p2, this._tempVector);
  9415. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9416. c = this._tempVector.lengthSquared() - 1.0;
  9417. lowestRoot = getLowestRoot(a, b, c, t);
  9418. if (lowestRoot.found) {
  9419. t = lowestRoot.root;
  9420. found = true;
  9421. this._collisionPoint.copyFrom(p2);
  9422. }
  9423. this.basePoint.subtractToRef(p3, this._tempVector);
  9424. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9425. c = this._tempVector.lengthSquared() - 1.0;
  9426. lowestRoot = getLowestRoot(a, b, c, t);
  9427. if (lowestRoot.found) {
  9428. t = lowestRoot.root;
  9429. found = true;
  9430. this._collisionPoint.copyFrom(p3);
  9431. }
  9432. p2.subtractToRef(p1, this._edge);
  9433. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9434. var edgeSquaredLength = this._edge.lengthSquared();
  9435. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9436. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9437. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9438. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9439. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9440. lowestRoot = getLowestRoot(a, b, c, t);
  9441. if (lowestRoot.found) {
  9442. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9443. if (f >= 0.0 && f <= 1.0) {
  9444. t = lowestRoot.root;
  9445. found = true;
  9446. this._edge.scaleInPlace(f);
  9447. p1.addToRef(this._edge, this._collisionPoint);
  9448. }
  9449. }
  9450. p3.subtractToRef(p2, this._edge);
  9451. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9452. edgeSquaredLength = this._edge.lengthSquared();
  9453. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9454. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9455. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9456. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9457. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9458. lowestRoot = getLowestRoot(a, b, c, t);
  9459. if (lowestRoot.found) {
  9460. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9461. if (f >= 0.0 && f <= 1.0) {
  9462. t = lowestRoot.root;
  9463. found = true;
  9464. this._edge.scaleInPlace(f);
  9465. p2.addToRef(this._edge, this._collisionPoint);
  9466. }
  9467. }
  9468. p1.subtractToRef(p3, this._edge);
  9469. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9470. edgeSquaredLength = this._edge.lengthSquared();
  9471. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9472. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9473. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9474. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9475. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9476. lowestRoot = getLowestRoot(a, b, c, t);
  9477. if (lowestRoot.found) {
  9478. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9479. if (f >= 0.0 && f <= 1.0) {
  9480. t = lowestRoot.root;
  9481. found = true;
  9482. this._edge.scaleInPlace(f);
  9483. p3.addToRef(this._edge, this._collisionPoint);
  9484. }
  9485. }
  9486. }
  9487. if (found) {
  9488. var distToCollision = t * this.velocity.length();
  9489. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9490. if (!this.intersectionPoint) {
  9491. this.intersectionPoint = this._collisionPoint.clone();
  9492. }
  9493. else {
  9494. this.intersectionPoint.copyFrom(this._collisionPoint);
  9495. }
  9496. this.nearestDistance = distToCollision;
  9497. this.collisionFound = true;
  9498. }
  9499. }
  9500. };
  9501. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9502. for (var i = indexStart; i < indexEnd; i += 3) {
  9503. var p1 = pts[indices[i] - decal];
  9504. var p2 = pts[indices[i + 1] - decal];
  9505. var p3 = pts[indices[i + 2] - decal];
  9506. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9507. }
  9508. };
  9509. Collider.prototype._getResponse = function (pos, vel) {
  9510. pos.addToRef(vel, this._destinationPoint);
  9511. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9512. this.basePoint.addToRef(vel, pos);
  9513. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9514. this._slidePlaneNormal.normalize();
  9515. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9516. pos.addInPlace(this._displacementVector);
  9517. this.intersectionPoint.addInPlace(this._displacementVector);
  9518. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9519. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9520. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9521. };
  9522. return Collider;
  9523. })();
  9524. BABYLON.Collider = Collider;
  9525. })(BABYLON || (BABYLON = {}));
  9526. var BABYLON;
  9527. (function (BABYLON) {
  9528. //WebWorker code will be inserted to this variable.
  9529. BABYLON.CollisionWorker = "";
  9530. (function (WorkerTaskType) {
  9531. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9532. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9533. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9534. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9535. var WorkerTaskType = BABYLON.WorkerTaskType;
  9536. (function (WorkerReplyType) {
  9537. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9538. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9539. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9540. var WorkerReplyType = BABYLON.WorkerReplyType;
  9541. var CollisionCoordinatorWorker = (function () {
  9542. function CollisionCoordinatorWorker() {
  9543. var _this = this;
  9544. this._scaledPosition = BABYLON.Vector3.Zero();
  9545. this._scaledVelocity = BABYLON.Vector3.Zero();
  9546. this.onMeshUpdated = function (mesh) {
  9547. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9548. };
  9549. this.onGeometryUpdated = function (geometry) {
  9550. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9551. };
  9552. this._afterRender = function () {
  9553. if (!_this._init)
  9554. return;
  9555. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9556. return;
  9557. }
  9558. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9559. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9560. if (_this._runningUpdated > 4) {
  9561. return;
  9562. }
  9563. ++_this._runningUpdated;
  9564. var payload = {
  9565. updatedMeshes: _this._addUpdateMeshesList,
  9566. updatedGeometries: _this._addUpdateGeometriesList,
  9567. removedGeometries: _this._toRemoveGeometryArray,
  9568. removedMeshes: _this._toRemoveMeshesArray
  9569. };
  9570. var message = {
  9571. payload: payload,
  9572. taskType: WorkerTaskType.UPDATE
  9573. };
  9574. var serializable = [];
  9575. for (var id in payload.updatedGeometries) {
  9576. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9577. //prepare transferables
  9578. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9579. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9580. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9581. }
  9582. }
  9583. _this._worker.postMessage(message, serializable);
  9584. _this._addUpdateMeshesList = {};
  9585. _this._addUpdateGeometriesList = {};
  9586. _this._toRemoveGeometryArray = [];
  9587. _this._toRemoveMeshesArray = [];
  9588. };
  9589. this._onMessageFromWorker = function (e) {
  9590. var returnData = e.data;
  9591. if (returnData.error != WorkerReplyType.SUCCESS) {
  9592. //TODO what errors can be returned from the worker?
  9593. BABYLON.Tools.Warn("error returned from worker!");
  9594. return;
  9595. }
  9596. switch (returnData.taskType) {
  9597. case WorkerTaskType.INIT:
  9598. _this._init = true;
  9599. //Update the worked with ALL of the scene's current state
  9600. _this._scene.meshes.forEach(function (mesh) {
  9601. _this.onMeshAdded(mesh);
  9602. });
  9603. _this._scene.getGeometries().forEach(function (geometry) {
  9604. _this.onGeometryAdded(geometry);
  9605. });
  9606. break;
  9607. case WorkerTaskType.UPDATE:
  9608. _this._runningUpdated--;
  9609. break;
  9610. case WorkerTaskType.COLLIDE:
  9611. _this._runningCollisionTask = false;
  9612. var returnPayload = returnData.payload;
  9613. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9614. return;
  9615. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9616. //cleanup
  9617. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9618. break;
  9619. }
  9620. };
  9621. this._collisionsCallbackArray = [];
  9622. this._init = false;
  9623. this._runningUpdated = 0;
  9624. this._runningCollisionTask = false;
  9625. this._addUpdateMeshesList = {};
  9626. this._addUpdateGeometriesList = {};
  9627. this._toRemoveGeometryArray = [];
  9628. this._toRemoveMeshesArray = [];
  9629. }
  9630. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9631. if (!this._init)
  9632. return;
  9633. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9634. return;
  9635. position.divideToRef(collider.radius, this._scaledPosition);
  9636. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9637. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9638. var payload = {
  9639. collider: {
  9640. position: this._scaledPosition.asArray(),
  9641. velocity: this._scaledVelocity.asArray(),
  9642. radius: collider.radius.asArray()
  9643. },
  9644. collisionId: collisionIndex,
  9645. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9646. maximumRetry: maximumRetry
  9647. };
  9648. var message = {
  9649. payload: payload,
  9650. taskType: WorkerTaskType.COLLIDE
  9651. };
  9652. this._worker.postMessage(message);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9655. this._scene = scene;
  9656. this._scene.registerAfterRender(this._afterRender);
  9657. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9658. this._worker = new Worker(workerUrl);
  9659. this._worker.onmessage = this._onMessageFromWorker;
  9660. var message = {
  9661. payload: {},
  9662. taskType: WorkerTaskType.INIT
  9663. };
  9664. this._worker.postMessage(message);
  9665. };
  9666. CollisionCoordinatorWorker.prototype.destroy = function () {
  9667. this._scene.unregisterAfterRender(this._afterRender);
  9668. this._worker.terminate();
  9669. };
  9670. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9671. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9672. this.onMeshUpdated(mesh);
  9673. };
  9674. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9675. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9676. };
  9677. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9678. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9679. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9680. this.onGeometryUpdated(geometry);
  9681. };
  9682. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9683. this._toRemoveGeometryArray.push(geometry.id);
  9684. };
  9685. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9686. var submeshes = [];
  9687. if (mesh.subMeshes) {
  9688. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9689. return {
  9690. position: idx,
  9691. verticesStart: sm.verticesStart,
  9692. verticesCount: sm.verticesCount,
  9693. indexStart: sm.indexStart,
  9694. indexCount: sm.indexCount,
  9695. hasMaterial: !!sm.getMaterial(),
  9696. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9697. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9698. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9699. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9700. };
  9701. });
  9702. }
  9703. var geometryId = null;
  9704. if (mesh instanceof BABYLON.Mesh) {
  9705. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9706. }
  9707. else if (mesh instanceof BABYLON.InstancedMesh) {
  9708. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9709. }
  9710. return {
  9711. uniqueId: mesh.uniqueId,
  9712. id: mesh.id,
  9713. name: mesh.name,
  9714. geometryId: geometryId,
  9715. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9716. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9717. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9718. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9719. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9720. subMeshes: submeshes,
  9721. checkCollisions: mesh.checkCollisions
  9722. };
  9723. };
  9724. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9725. return {
  9726. id: geometry.id,
  9727. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9728. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9729. indices: new Int32Array(geometry.getIndices() || []),
  9730. };
  9731. };
  9732. return CollisionCoordinatorWorker;
  9733. })();
  9734. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9735. var CollisionCoordinatorLegacy = (function () {
  9736. function CollisionCoordinatorLegacy() {
  9737. this._scaledPosition = BABYLON.Vector3.Zero();
  9738. this._scaledVelocity = BABYLON.Vector3.Zero();
  9739. this._finalPosition = BABYLON.Vector3.Zero();
  9740. }
  9741. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9742. position.divideToRef(collider.radius, this._scaledPosition);
  9743. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9744. collider.collidedMesh = null;
  9745. collider.retry = 0;
  9746. collider.initialVelocity = this._scaledVelocity;
  9747. collider.initialPosition = this._scaledPosition;
  9748. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9749. this._finalPosition.multiplyInPlace(collider.radius);
  9750. //run the callback
  9751. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9752. };
  9753. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9754. this._scene = scene;
  9755. };
  9756. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9757. //Legacy need no destruction method.
  9758. };
  9759. //No update in legacy mode
  9760. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9761. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9762. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9763. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9764. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9765. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9766. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9767. if (excludedMesh === void 0) { excludedMesh = null; }
  9768. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9769. if (collider.retry >= maximumRetry) {
  9770. finalPosition.copyFrom(position);
  9771. return;
  9772. }
  9773. collider._initialize(position, velocity, closeDistance);
  9774. // Check all meshes
  9775. for (var index = 0; index < this._scene.meshes.length; index++) {
  9776. var mesh = this._scene.meshes[index];
  9777. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9778. mesh._checkCollision(collider);
  9779. }
  9780. }
  9781. if (!collider.collisionFound) {
  9782. position.addToRef(velocity, finalPosition);
  9783. return;
  9784. }
  9785. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9786. collider._getResponse(position, velocity);
  9787. }
  9788. if (velocity.length() <= closeDistance) {
  9789. finalPosition.copyFrom(position);
  9790. return;
  9791. }
  9792. collider.retry++;
  9793. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9794. };
  9795. return CollisionCoordinatorLegacy;
  9796. })();
  9797. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9798. })(BABYLON || (BABYLON = {}));
  9799. var BABYLON;
  9800. (function (BABYLON) {
  9801. var VRCameraMetrics = (function () {
  9802. function VRCameraMetrics() {
  9803. this.compensateDistortion = true;
  9804. }
  9805. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9806. get: function () {
  9807. return this.hResolution / (2 * this.vResolution);
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9813. get: function () {
  9814. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9820. get: function () {
  9821. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9822. var h = (4 * meters) / this.hScreenSize;
  9823. return BABYLON.Matrix.Translation(h, 0, 0);
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9829. get: function () {
  9830. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9831. var h = (4 * meters) / this.hScreenSize;
  9832. return BABYLON.Matrix.Translation(-h, 0, 0);
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9838. get: function () {
  9839. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9845. get: function () {
  9846. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. VRCameraMetrics.GetDefault = function () {
  9852. var result = new VRCameraMetrics();
  9853. result.hResolution = 1280;
  9854. result.vResolution = 800;
  9855. result.hScreenSize = 0.149759993;
  9856. result.vScreenSize = 0.0935999975;
  9857. result.vScreenCenter = 0.0467999987,
  9858. result.eyeToScreenDistance = 0.0410000011;
  9859. result.lensSeparationDistance = 0.0635000020;
  9860. result.interpupillaryDistance = 0.0640000030;
  9861. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9862. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9863. result.postProcessScaleFactor = 1.714605507808412;
  9864. result.lensCenterOffset = 0.151976421;
  9865. return result;
  9866. };
  9867. return VRCameraMetrics;
  9868. })();
  9869. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9870. var Camera = (function (_super) {
  9871. __extends(Camera, _super);
  9872. function Camera(name, position, scene) {
  9873. _super.call(this, name, scene);
  9874. this.position = position;
  9875. // Members
  9876. this.upVector = BABYLON.Vector3.Up();
  9877. this.orthoLeft = null;
  9878. this.orthoRight = null;
  9879. this.orthoBottom = null;
  9880. this.orthoTop = null;
  9881. this.fov = 0.8;
  9882. this.minZ = 1.0;
  9883. this.maxZ = 10000.0;
  9884. this.inertia = 0.9;
  9885. this.mode = Camera.PERSPECTIVE_CAMERA;
  9886. this.isIntermediate = false;
  9887. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9888. this.layerMask = 0x0FFFFFFF;
  9889. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9890. // Camera rig members
  9891. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9892. this._rigCameras = new Array();
  9893. // Cache
  9894. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9895. this._projectionMatrix = new BABYLON.Matrix();
  9896. this._postProcesses = new Array();
  9897. this._postProcessesTakenIndices = [];
  9898. this._activeMeshes = new BABYLON.SmartArray(256);
  9899. this._globalPosition = BABYLON.Vector3.Zero();
  9900. scene.addCamera(this);
  9901. if (!scene.activeCamera) {
  9902. scene.activeCamera = this;
  9903. }
  9904. }
  9905. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9906. get: function () {
  9907. return Camera._PERSPECTIVE_CAMERA;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9913. get: function () {
  9914. return Camera._ORTHOGRAPHIC_CAMERA;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9920. get: function () {
  9921. return Camera._FOVMODE_VERTICAL_FIXED;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9927. get: function () {
  9928. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9934. get: function () {
  9935. return Camera._RIG_MODE_NONE;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9941. get: function () {
  9942. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9948. get: function () {
  9949. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9955. get: function () {
  9956. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9962. get: function () {
  9963. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9969. get: function () {
  9970. return Camera._RIG_MODE_VR;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Camera.prototype, "globalPosition", {
  9976. get: function () {
  9977. return this._globalPosition;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Camera.prototype.getActiveMeshes = function () {
  9983. return this._activeMeshes;
  9984. };
  9985. Camera.prototype.isActiveMesh = function (mesh) {
  9986. return (this._activeMeshes.indexOf(mesh) !== -1);
  9987. };
  9988. //Cache
  9989. Camera.prototype._initCache = function () {
  9990. _super.prototype._initCache.call(this);
  9991. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9992. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9993. this._cache.mode = undefined;
  9994. this._cache.minZ = undefined;
  9995. this._cache.maxZ = undefined;
  9996. this._cache.fov = undefined;
  9997. this._cache.aspectRatio = undefined;
  9998. this._cache.orthoLeft = undefined;
  9999. this._cache.orthoRight = undefined;
  10000. this._cache.orthoBottom = undefined;
  10001. this._cache.orthoTop = undefined;
  10002. this._cache.renderWidth = undefined;
  10003. this._cache.renderHeight = undefined;
  10004. };
  10005. Camera.prototype._updateCache = function (ignoreParentClass) {
  10006. if (!ignoreParentClass) {
  10007. _super.prototype._updateCache.call(this);
  10008. }
  10009. var engine = this.getEngine();
  10010. this._cache.position.copyFrom(this.position);
  10011. this._cache.upVector.copyFrom(this.upVector);
  10012. this._cache.mode = this.mode;
  10013. this._cache.minZ = this.minZ;
  10014. this._cache.maxZ = this.maxZ;
  10015. this._cache.fov = this.fov;
  10016. this._cache.aspectRatio = engine.getAspectRatio(this);
  10017. this._cache.orthoLeft = this.orthoLeft;
  10018. this._cache.orthoRight = this.orthoRight;
  10019. this._cache.orthoBottom = this.orthoBottom;
  10020. this._cache.orthoTop = this.orthoTop;
  10021. this._cache.renderWidth = engine.getRenderWidth();
  10022. this._cache.renderHeight = engine.getRenderHeight();
  10023. };
  10024. Camera.prototype._updateFromScene = function () {
  10025. this.updateCache();
  10026. this._update();
  10027. };
  10028. // Synchronized
  10029. Camera.prototype._isSynchronized = function () {
  10030. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10031. };
  10032. Camera.prototype._isSynchronizedViewMatrix = function () {
  10033. if (!_super.prototype._isSynchronized.call(this))
  10034. return false;
  10035. return this._cache.position.equals(this.position)
  10036. && this._cache.upVector.equals(this.upVector)
  10037. && this.isSynchronizedWithParent();
  10038. };
  10039. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10040. var check = this._cache.mode === this.mode
  10041. && this._cache.minZ === this.minZ
  10042. && this._cache.maxZ === this.maxZ;
  10043. if (!check) {
  10044. return false;
  10045. }
  10046. var engine = this.getEngine();
  10047. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10048. check = this._cache.fov === this.fov
  10049. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10050. }
  10051. else {
  10052. check = this._cache.orthoLeft === this.orthoLeft
  10053. && this._cache.orthoRight === this.orthoRight
  10054. && this._cache.orthoBottom === this.orthoBottom
  10055. && this._cache.orthoTop === this.orthoTop
  10056. && this._cache.renderWidth === engine.getRenderWidth()
  10057. && this._cache.renderHeight === engine.getRenderHeight();
  10058. }
  10059. return check;
  10060. };
  10061. // Controls
  10062. Camera.prototype.attachControl = function (element) {
  10063. };
  10064. Camera.prototype.detachControl = function (element) {
  10065. };
  10066. Camera.prototype._update = function () {
  10067. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10068. this._updateRigCameras();
  10069. }
  10070. this._checkInputs();
  10071. };
  10072. Camera.prototype._checkInputs = function () {
  10073. };
  10074. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10075. if (insertAt === void 0) { insertAt = null; }
  10076. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10077. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10078. return 0;
  10079. }
  10080. if (insertAt == null || insertAt < 0) {
  10081. this._postProcesses.push(postProcess);
  10082. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10083. return this._postProcesses.length - 1;
  10084. }
  10085. var add = 0;
  10086. var i;
  10087. var start;
  10088. if (this._postProcesses[insertAt]) {
  10089. start = this._postProcesses.length - 1;
  10090. for (i = start; i >= insertAt + 1; --i) {
  10091. this._postProcesses[i + 1] = this._postProcesses[i];
  10092. }
  10093. add = 1;
  10094. }
  10095. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10096. if (this._postProcessesTakenIndices[i] < insertAt) {
  10097. continue;
  10098. }
  10099. start = this._postProcessesTakenIndices.length - 1;
  10100. for (var j = start; j >= i; --j) {
  10101. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10102. }
  10103. this._postProcessesTakenIndices[i] = insertAt;
  10104. break;
  10105. }
  10106. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10107. this._postProcessesTakenIndices.push(insertAt);
  10108. }
  10109. var result = insertAt + add;
  10110. this._postProcesses[result] = postProcess;
  10111. return result;
  10112. };
  10113. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10114. if (atIndices === void 0) { atIndices = null; }
  10115. var result = [];
  10116. var i;
  10117. var index;
  10118. if (!atIndices) {
  10119. var length = this._postProcesses.length;
  10120. for (i = 0; i < length; i++) {
  10121. if (this._postProcesses[i] !== postProcess) {
  10122. continue;
  10123. }
  10124. delete this._postProcesses[i];
  10125. index = this._postProcessesTakenIndices.indexOf(i);
  10126. this._postProcessesTakenIndices.splice(index, 1);
  10127. }
  10128. }
  10129. else {
  10130. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10131. for (i = 0; i < atIndices.length; i++) {
  10132. var foundPostProcess = this._postProcesses[atIndices[i]];
  10133. if (foundPostProcess !== postProcess) {
  10134. result.push(i);
  10135. continue;
  10136. }
  10137. delete this._postProcesses[atIndices[i]];
  10138. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10139. this._postProcessesTakenIndices.splice(index, 1);
  10140. }
  10141. }
  10142. return result;
  10143. };
  10144. Camera.prototype.getWorldMatrix = function () {
  10145. if (!this._worldMatrix) {
  10146. this._worldMatrix = BABYLON.Matrix.Identity();
  10147. }
  10148. var viewMatrix = this.getViewMatrix();
  10149. viewMatrix.invertToRef(this._worldMatrix);
  10150. return this._worldMatrix;
  10151. };
  10152. Camera.prototype._getViewMatrix = function () {
  10153. return BABYLON.Matrix.Identity();
  10154. };
  10155. Camera.prototype.getViewMatrix = function (force) {
  10156. this._computedViewMatrix = this._computeViewMatrix(force);
  10157. if (!force && this._isSynchronizedViewMatrix()) {
  10158. return this._computedViewMatrix;
  10159. }
  10160. if (!this.parent || !this.parent.getWorldMatrix) {
  10161. this._globalPosition.copyFrom(this.position);
  10162. }
  10163. else {
  10164. if (!this._worldMatrix) {
  10165. this._worldMatrix = BABYLON.Matrix.Identity();
  10166. }
  10167. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10168. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10169. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10170. this._computedViewMatrix.invert();
  10171. this._markSyncedWithParent();
  10172. }
  10173. this._currentRenderId = this.getScene().getRenderId();
  10174. return this._computedViewMatrix;
  10175. };
  10176. Camera.prototype._computeViewMatrix = function (force) {
  10177. if (!force && this._isSynchronizedViewMatrix()) {
  10178. return this._computedViewMatrix;
  10179. }
  10180. this._computedViewMatrix = this._getViewMatrix();
  10181. this._currentRenderId = this.getScene().getRenderId();
  10182. return this._computedViewMatrix;
  10183. };
  10184. Camera.prototype.getProjectionMatrix = function (force) {
  10185. if (!force && this._isSynchronizedProjectionMatrix()) {
  10186. return this._projectionMatrix;
  10187. }
  10188. var engine = this.getEngine();
  10189. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10190. if (this.minZ <= 0) {
  10191. this.minZ = 0.1;
  10192. }
  10193. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10194. return this._projectionMatrix;
  10195. }
  10196. var halfWidth = engine.getRenderWidth() / 2.0;
  10197. var halfHeight = engine.getRenderHeight() / 2.0;
  10198. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10199. return this._projectionMatrix;
  10200. };
  10201. Camera.prototype.dispose = function () {
  10202. // Animations
  10203. this.getScene().stopAnimation(this);
  10204. // Remove from scene
  10205. this.getScene().removeCamera(this);
  10206. while (this._rigCameras.length > 0) {
  10207. this._rigCameras.pop().dispose();
  10208. }
  10209. // Postprocesses
  10210. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10211. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10212. }
  10213. };
  10214. // ---- Camera rigs section ----
  10215. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10216. while (this._rigCameras.length > 0) {
  10217. this._rigCameras.pop().dispose();
  10218. }
  10219. this.cameraRigMode = mode;
  10220. this._cameraRigParams = {};
  10221. switch (this.cameraRigMode) {
  10222. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10223. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10224. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10225. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10226. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10227. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10228. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10229. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10230. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10231. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10232. break;
  10233. }
  10234. var postProcesses = new Array();
  10235. switch (this.cameraRigMode) {
  10236. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10237. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10238. this._rigCameras[0].isIntermediate = true;
  10239. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10240. postProcesses[1].onApply = function (effect) {
  10241. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10242. };
  10243. break;
  10244. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10245. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10246. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10247. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10248. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10249. var secondCamIndex = 1 - firstCamIndex;
  10250. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10251. this._rigCameras[firstCamIndex].isIntermediate = true;
  10252. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10253. break;
  10254. case Camera.RIG_MODE_VR:
  10255. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10256. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10257. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10258. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10259. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10260. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10261. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10262. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10263. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10264. if (metrics.compensateDistortion) {
  10265. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10266. }
  10267. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10268. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10269. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10270. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10271. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10272. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10273. if (metrics.compensateDistortion) {
  10274. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10275. }
  10276. break;
  10277. }
  10278. this._update();
  10279. };
  10280. Camera.prototype._getVRProjectionMatrix = function () {
  10281. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10282. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10283. return this._projectionMatrix;
  10284. };
  10285. Camera.prototype.setCameraRigParameter = function (name, value) {
  10286. this._cameraRigParams[name] = value;
  10287. //provisionnally:
  10288. if (name === "interaxialDistance") {
  10289. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10290. }
  10291. };
  10292. /**
  10293. * May needs to be overridden by children so sub has required properties to be copied
  10294. */
  10295. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10296. return null;
  10297. };
  10298. /**
  10299. * May needs to be overridden by children
  10300. */
  10301. Camera.prototype._updateRigCameras = function () {
  10302. for (var i = 0; i < this._rigCameras.length; i++) {
  10303. this._rigCameras[i].minZ = this.minZ;
  10304. this._rigCameras[i].maxZ = this.maxZ;
  10305. this._rigCameras[i].fov = this.fov;
  10306. }
  10307. // only update viewport when ANAGLYPH
  10308. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10309. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10310. }
  10311. };
  10312. Camera.prototype.serialize = function () {
  10313. var serializationObject = {};
  10314. serializationObject.name = this.name;
  10315. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10316. serializationObject.id = this.id;
  10317. serializationObject.position = this.position.asArray();
  10318. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10319. // Parent
  10320. if (this.parent) {
  10321. serializationObject.parentId = this.parent.id;
  10322. }
  10323. serializationObject.fov = this.fov;
  10324. serializationObject.minZ = this.minZ;
  10325. serializationObject.maxZ = this.maxZ;
  10326. serializationObject.inertia = this.inertia;
  10327. // Animations
  10328. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10329. // Layer mask
  10330. serializationObject.layerMask = this.layerMask;
  10331. return serializationObject;
  10332. };
  10333. Camera.Parse = function (parsedCamera, scene) {
  10334. var camera;
  10335. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10336. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10337. var interaxial_distance;
  10338. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10339. var alpha = parsedCamera.alpha;
  10340. var beta = parsedCamera.beta;
  10341. var radius = parsedCamera.radius;
  10342. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10343. interaxial_distance = parsedCamera.interaxial_distance;
  10344. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10345. }
  10346. else {
  10347. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10348. }
  10349. }
  10350. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10351. interaxial_distance = parsedCamera.interaxial_distance;
  10352. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10353. }
  10354. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10355. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10356. }
  10357. else if (parsedCamera.type === "FollowCamera") {
  10358. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10359. camera.heightOffset = parsedCamera.heightOffset;
  10360. camera.radius = parsedCamera.radius;
  10361. camera.rotationOffset = parsedCamera.rotationOffset;
  10362. if (lockedTargetMesh)
  10363. camera.target = lockedTargetMesh;
  10364. }
  10365. else if (parsedCamera.type === "GamepadCamera") {
  10366. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10367. }
  10368. else if (parsedCamera.type === "TouchCamera") {
  10369. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10370. }
  10371. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10372. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10373. }
  10374. else if (parsedCamera.type === "WebVRFreeCamera") {
  10375. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10376. }
  10377. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10378. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10379. }
  10380. else {
  10381. // Free Camera is the default value
  10382. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10383. }
  10384. // apply 3d rig, when found
  10385. if (parsedCamera.cameraRigMode) {
  10386. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10387. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10388. }
  10389. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10390. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10391. camera.lockedTarget = lockedTargetMesh;
  10392. }
  10393. camera.id = parsedCamera.id;
  10394. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10395. // Parent
  10396. if (parsedCamera.parentId) {
  10397. camera._waitingParentId = parsedCamera.parentId;
  10398. }
  10399. // Target
  10400. if (parsedCamera.target) {
  10401. if (camera.setTarget) {
  10402. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10403. }
  10404. else {
  10405. //For ArcRotate
  10406. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10407. }
  10408. }
  10409. else {
  10410. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10411. }
  10412. camera.fov = parsedCamera.fov;
  10413. camera.minZ = parsedCamera.minZ;
  10414. camera.maxZ = parsedCamera.maxZ;
  10415. camera.speed = parsedCamera.speed;
  10416. camera.inertia = parsedCamera.inertia;
  10417. camera.checkCollisions = parsedCamera.checkCollisions;
  10418. camera.applyGravity = parsedCamera.applyGravity;
  10419. if (parsedCamera.ellipsoid) {
  10420. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10421. }
  10422. // Animations
  10423. if (parsedCamera.animations) {
  10424. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10425. var parsedAnimation = parsedCamera.animations[animationIndex];
  10426. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10427. }
  10428. }
  10429. if (parsedCamera.autoAnimate) {
  10430. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10431. }
  10432. // Layer Mask
  10433. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10434. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10435. }
  10436. else {
  10437. camera.layerMask = 0x0FFFFFFF;
  10438. }
  10439. return camera;
  10440. };
  10441. // Statics
  10442. Camera._PERSPECTIVE_CAMERA = 0;
  10443. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10444. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10445. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10446. Camera._RIG_MODE_NONE = 0;
  10447. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10448. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10449. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10450. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10451. Camera._RIG_MODE_VR = 20;
  10452. return Camera;
  10453. })(BABYLON.Node);
  10454. BABYLON.Camera = Camera;
  10455. })(BABYLON || (BABYLON = {}));
  10456. var BABYLON;
  10457. (function (BABYLON) {
  10458. var TargetCamera = (function (_super) {
  10459. __extends(TargetCamera, _super);
  10460. function TargetCamera(name, position, scene) {
  10461. _super.call(this, name, position, scene);
  10462. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10463. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10464. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10465. this.speed = 2.0;
  10466. this.noRotationConstraint = false;
  10467. this.lockedTarget = null;
  10468. this._currentTarget = BABYLON.Vector3.Zero();
  10469. this._viewMatrix = BABYLON.Matrix.Zero();
  10470. this._camMatrix = BABYLON.Matrix.Zero();
  10471. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10472. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10473. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10474. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10475. this._lookAtTemp = BABYLON.Matrix.Zero();
  10476. this._tempMatrix = BABYLON.Matrix.Zero();
  10477. }
  10478. TargetCamera.prototype.getFrontPosition = function (distance) {
  10479. var direction = this.getTarget().subtract(this.position);
  10480. direction.normalize();
  10481. direction.scaleInPlace(distance);
  10482. return this.globalPosition.add(direction);
  10483. };
  10484. TargetCamera.prototype._getLockedTargetPosition = function () {
  10485. if (!this.lockedTarget) {
  10486. return null;
  10487. }
  10488. return this.lockedTarget.position || this.lockedTarget;
  10489. };
  10490. // Cache
  10491. TargetCamera.prototype._initCache = function () {
  10492. _super.prototype._initCache.call(this);
  10493. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10494. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10495. };
  10496. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10497. if (!ignoreParentClass) {
  10498. _super.prototype._updateCache.call(this);
  10499. }
  10500. var lockedTargetPosition = this._getLockedTargetPosition();
  10501. if (!lockedTargetPosition) {
  10502. this._cache.lockedTarget = null;
  10503. }
  10504. else {
  10505. if (!this._cache.lockedTarget) {
  10506. this._cache.lockedTarget = lockedTargetPosition.clone();
  10507. }
  10508. else {
  10509. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10510. }
  10511. }
  10512. this._cache.rotation.copyFrom(this.rotation);
  10513. };
  10514. // Synchronized
  10515. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10516. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10517. return false;
  10518. }
  10519. var lockedTargetPosition = this._getLockedTargetPosition();
  10520. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10521. && this._cache.rotation.equals(this.rotation);
  10522. };
  10523. // Methods
  10524. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10525. var engine = this.getEngine();
  10526. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10527. };
  10528. // Target
  10529. TargetCamera.prototype.setTarget = function (target) {
  10530. this.upVector.normalize();
  10531. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10532. this._camMatrix.invert();
  10533. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10534. var vDir = target.subtract(this.position);
  10535. if (vDir.x >= 0.0) {
  10536. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10537. }
  10538. else {
  10539. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10540. }
  10541. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10542. if (isNaN(this.rotation.x)) {
  10543. this.rotation.x = 0;
  10544. }
  10545. if (isNaN(this.rotation.y)) {
  10546. this.rotation.y = 0;
  10547. }
  10548. if (isNaN(this.rotation.z)) {
  10549. this.rotation.z = 0;
  10550. }
  10551. };
  10552. TargetCamera.prototype.getTarget = function () {
  10553. return this._currentTarget;
  10554. };
  10555. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10556. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10557. };
  10558. TargetCamera.prototype._updatePosition = function () {
  10559. this.position.addInPlace(this.cameraDirection);
  10560. };
  10561. TargetCamera.prototype._checkInputs = function () {
  10562. var needToMove = this._decideIfNeedsToMove();
  10563. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10564. // Move
  10565. if (needToMove) {
  10566. this._updatePosition();
  10567. }
  10568. // Rotate
  10569. if (needToRotate) {
  10570. this.rotation.x += this.cameraRotation.x;
  10571. this.rotation.y += this.cameraRotation.y;
  10572. if (!this.noRotationConstraint) {
  10573. var limit = (Math.PI / 2) * 0.95;
  10574. if (this.rotation.x > limit)
  10575. this.rotation.x = limit;
  10576. if (this.rotation.x < -limit)
  10577. this.rotation.x = -limit;
  10578. }
  10579. }
  10580. // Inertia
  10581. if (needToMove) {
  10582. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10583. this.cameraDirection.x = 0;
  10584. }
  10585. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10586. this.cameraDirection.y = 0;
  10587. }
  10588. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10589. this.cameraDirection.z = 0;
  10590. }
  10591. this.cameraDirection.scaleInPlace(this.inertia);
  10592. }
  10593. if (needToRotate) {
  10594. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10595. this.cameraRotation.x = 0;
  10596. }
  10597. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10598. this.cameraRotation.y = 0;
  10599. }
  10600. this.cameraRotation.scaleInPlace(this.inertia);
  10601. }
  10602. _super.prototype._checkInputs.call(this);
  10603. };
  10604. TargetCamera.prototype._getViewMatrix = function () {
  10605. if (!this.lockedTarget) {
  10606. // Compute
  10607. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10608. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10609. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10610. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10611. this._lookAtTemp.invert();
  10612. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10613. }
  10614. else {
  10615. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10616. }
  10617. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10618. // Computing target and final matrix
  10619. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10620. }
  10621. else {
  10622. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10623. }
  10624. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10625. return this._viewMatrix;
  10626. };
  10627. TargetCamera.prototype._getVRViewMatrix = function () {
  10628. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10629. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10630. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10631. // Computing target and final matrix
  10632. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10633. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10634. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10635. return this._viewMatrix;
  10636. };
  10637. /**
  10638. * @override
  10639. * Override Camera.createRigCamera
  10640. */
  10641. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10642. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10643. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10644. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10645. rigCamera._cameraRigParams = {};
  10646. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10647. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10648. }
  10649. return rigCamera;
  10650. }
  10651. return null;
  10652. };
  10653. /**
  10654. * @override
  10655. * Override Camera._updateRigCameras
  10656. */
  10657. TargetCamera.prototype._updateRigCameras = function () {
  10658. switch (this.cameraRigMode) {
  10659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10663. case BABYLON.Camera.RIG_MODE_VR:
  10664. var camLeft = this._rigCameras[0];
  10665. var camRight = this._rigCameras[1];
  10666. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10667. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10668. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10669. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10670. camLeft.position.copyFrom(this.position);
  10671. camRight.position.copyFrom(this.position);
  10672. }
  10673. else {
  10674. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10675. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10676. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10677. camLeft.setTarget(this.getTarget());
  10678. camRight.setTarget(this.getTarget());
  10679. }
  10680. break;
  10681. }
  10682. _super.prototype._updateRigCameras.call(this);
  10683. };
  10684. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10685. if (!this._rigCamTransformMatrix) {
  10686. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10687. }
  10688. var target = this.getTarget();
  10689. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10690. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10691. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10692. };
  10693. TargetCamera.prototype.serialize = function () {
  10694. var serializationObject = _super.prototype.serialize.call(this);
  10695. serializationObject.speed = this.speed;
  10696. if (this.rotation) {
  10697. serializationObject.rotation = this.rotation.asArray();
  10698. }
  10699. if (this.lockedTarget && this.lockedTarget.id) {
  10700. serializationObject.lockedTargetId = this.lockedTarget.id;
  10701. }
  10702. return serializationObject;
  10703. };
  10704. return TargetCamera;
  10705. })(BABYLON.Camera);
  10706. BABYLON.TargetCamera = TargetCamera;
  10707. })(BABYLON || (BABYLON = {}));
  10708. var BABYLON;
  10709. (function (BABYLON) {
  10710. var FreeCamera = (function (_super) {
  10711. __extends(FreeCamera, _super);
  10712. function FreeCamera(name, position, scene) {
  10713. var _this = this;
  10714. _super.call(this, name, position, scene);
  10715. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10716. this.keysUp = [38];
  10717. this.keysDown = [40];
  10718. this.keysLeft = [37];
  10719. this.keysRight = [39];
  10720. this.checkCollisions = false;
  10721. this.applyGravity = false;
  10722. this.angularSensibility = 2000.0;
  10723. this._keys = [];
  10724. this._collider = new BABYLON.Collider();
  10725. this._needMoveForGravity = false;
  10726. this._oldPosition = BABYLON.Vector3.Zero();
  10727. this._diffPosition = BABYLON.Vector3.Zero();
  10728. this._newPosition = BABYLON.Vector3.Zero();
  10729. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10730. if (collidedMesh === void 0) { collidedMesh = null; }
  10731. //TODO move this to the collision coordinator!
  10732. if (_this.getScene().workerCollisions)
  10733. newPosition.multiplyInPlace(_this._collider.radius);
  10734. var updatePosition = function (newPos) {
  10735. _this._newPosition.copyFrom(newPos);
  10736. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10737. var oldPosition = _this.position.clone();
  10738. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10739. _this.position.addInPlace(_this._diffPosition);
  10740. if (_this.onCollide && collidedMesh) {
  10741. _this.onCollide(collidedMesh);
  10742. }
  10743. }
  10744. };
  10745. updatePosition(newPosition);
  10746. };
  10747. }
  10748. // Controls
  10749. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10750. var _this = this;
  10751. var previousPosition;
  10752. var engine = this.getEngine();
  10753. if (this._attachedElement) {
  10754. return;
  10755. }
  10756. this._attachedElement = element;
  10757. if (this._onMouseDown === undefined) {
  10758. this._onMouseDown = function (evt) {
  10759. previousPosition = {
  10760. x: evt.clientX,
  10761. y: evt.clientY
  10762. };
  10763. if (!noPreventDefault) {
  10764. evt.preventDefault();
  10765. }
  10766. };
  10767. this._onMouseUp = function (evt) {
  10768. previousPosition = null;
  10769. if (!noPreventDefault) {
  10770. evt.preventDefault();
  10771. }
  10772. };
  10773. this._onMouseOut = function (evt) {
  10774. previousPosition = null;
  10775. _this._keys = [];
  10776. if (!noPreventDefault) {
  10777. evt.preventDefault();
  10778. }
  10779. };
  10780. this._onMouseMove = function (evt) {
  10781. if (!previousPosition && !engine.isPointerLock) {
  10782. return;
  10783. }
  10784. var offsetX;
  10785. var offsetY;
  10786. if (!engine.isPointerLock) {
  10787. offsetX = evt.clientX - previousPosition.x;
  10788. offsetY = evt.clientY - previousPosition.y;
  10789. }
  10790. else {
  10791. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10792. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10793. }
  10794. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10795. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10796. previousPosition = {
  10797. x: evt.clientX,
  10798. y: evt.clientY
  10799. };
  10800. if (!noPreventDefault) {
  10801. evt.preventDefault();
  10802. }
  10803. };
  10804. this._onKeyDown = function (evt) {
  10805. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10806. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10807. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10808. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10809. var index = _this._keys.indexOf(evt.keyCode);
  10810. if (index === -1) {
  10811. _this._keys.push(evt.keyCode);
  10812. }
  10813. if (!noPreventDefault) {
  10814. evt.preventDefault();
  10815. }
  10816. }
  10817. };
  10818. this._onKeyUp = function (evt) {
  10819. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10820. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10821. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10822. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10823. var index = _this._keys.indexOf(evt.keyCode);
  10824. if (index >= 0) {
  10825. _this._keys.splice(index, 1);
  10826. }
  10827. if (!noPreventDefault) {
  10828. evt.preventDefault();
  10829. }
  10830. }
  10831. };
  10832. this._onLostFocus = function () {
  10833. _this._keys = [];
  10834. };
  10835. this._reset = function () {
  10836. _this._keys = [];
  10837. previousPosition = null;
  10838. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10839. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10840. };
  10841. }
  10842. element.addEventListener("mousedown", this._onMouseDown, false);
  10843. element.addEventListener("mouseup", this._onMouseUp, false);
  10844. element.addEventListener("mouseout", this._onMouseOut, false);
  10845. element.addEventListener("mousemove", this._onMouseMove, false);
  10846. BABYLON.Tools.RegisterTopRootEvents([
  10847. { name: "keydown", handler: this._onKeyDown },
  10848. { name: "keyup", handler: this._onKeyUp },
  10849. { name: "blur", handler: this._onLostFocus }
  10850. ]);
  10851. };
  10852. FreeCamera.prototype.detachControl = function (element) {
  10853. if (this._attachedElement !== element) {
  10854. return;
  10855. }
  10856. element.removeEventListener("mousedown", this._onMouseDown);
  10857. element.removeEventListener("mouseup", this._onMouseUp);
  10858. element.removeEventListener("mouseout", this._onMouseOut);
  10859. element.removeEventListener("mousemove", this._onMouseMove);
  10860. BABYLON.Tools.UnregisterTopRootEvents([
  10861. { name: "keydown", handler: this._onKeyDown },
  10862. { name: "keyup", handler: this._onKeyUp },
  10863. { name: "blur", handler: this._onLostFocus }
  10864. ]);
  10865. this._attachedElement = null;
  10866. if (this._reset) {
  10867. this._reset();
  10868. }
  10869. };
  10870. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10871. var globalPosition;
  10872. if (this.parent) {
  10873. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10874. }
  10875. else {
  10876. globalPosition = this.position;
  10877. }
  10878. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10879. this._collider.radius = this.ellipsoid;
  10880. //no need for clone, as long as gravity is not on.
  10881. var actualVelocity = velocity;
  10882. //add gravity to the velocity to prevent the dual-collision checking
  10883. if (this.applyGravity) {
  10884. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10885. actualVelocity = velocity.add(this.getScene().gravity);
  10886. }
  10887. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10888. };
  10889. FreeCamera.prototype._checkInputs = function () {
  10890. if (!this._localDirection) {
  10891. this._localDirection = BABYLON.Vector3.Zero();
  10892. this._transformedDirection = BABYLON.Vector3.Zero();
  10893. }
  10894. // Keyboard
  10895. for (var index = 0; index < this._keys.length; index++) {
  10896. var keyCode = this._keys[index];
  10897. var speed = this._computeLocalCameraSpeed();
  10898. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10899. this._localDirection.copyFromFloats(-speed, 0, 0);
  10900. }
  10901. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10902. this._localDirection.copyFromFloats(0, 0, speed);
  10903. }
  10904. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10905. this._localDirection.copyFromFloats(speed, 0, 0);
  10906. }
  10907. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10908. this._localDirection.copyFromFloats(0, 0, -speed);
  10909. }
  10910. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10911. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10912. this.cameraDirection.addInPlace(this._transformedDirection);
  10913. }
  10914. _super.prototype._checkInputs.call(this);
  10915. };
  10916. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10917. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10918. };
  10919. FreeCamera.prototype._updatePosition = function () {
  10920. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10921. this._collideWithWorld(this.cameraDirection);
  10922. }
  10923. else {
  10924. this.position.addInPlace(this.cameraDirection);
  10925. }
  10926. };
  10927. FreeCamera.prototype.serialize = function () {
  10928. var serializationObject = _super.prototype.serialize.call(this);
  10929. serializationObject.checkCollisions = this.checkCollisions;
  10930. serializationObject.applyGravity = this.applyGravity;
  10931. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10932. return serializationObject;
  10933. };
  10934. return FreeCamera;
  10935. })(BABYLON.TargetCamera);
  10936. BABYLON.FreeCamera = FreeCamera;
  10937. })(BABYLON || (BABYLON = {}));
  10938. var BABYLON;
  10939. (function (BABYLON) {
  10940. var FollowCamera = (function (_super) {
  10941. __extends(FollowCamera, _super);
  10942. function FollowCamera(name, position, scene) {
  10943. _super.call(this, name, position, scene);
  10944. this.radius = 12;
  10945. this.rotationOffset = 0;
  10946. this.heightOffset = 4;
  10947. this.cameraAcceleration = 0.05;
  10948. this.maxCameraSpeed = 20;
  10949. }
  10950. FollowCamera.prototype.getRadians = function (degrees) {
  10951. return degrees * Math.PI / 180;
  10952. };
  10953. FollowCamera.prototype.follow = function (cameraTarget) {
  10954. if (!cameraTarget)
  10955. return;
  10956. var yRotation;
  10957. if (cameraTarget.rotationQuaternion) {
  10958. var rotMatrix = new BABYLON.Matrix();
  10959. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10960. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10961. }
  10962. else {
  10963. yRotation = cameraTarget.rotation.y;
  10964. }
  10965. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10966. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10967. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10968. var dx = targetX - this.position.x;
  10969. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10970. var dz = (targetZ) - this.position.z;
  10971. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10972. var vy = dy * this.cameraAcceleration;
  10973. var vz = dz * this.cameraAcceleration * 2;
  10974. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10975. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10976. }
  10977. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10978. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10979. }
  10980. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10981. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10982. }
  10983. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10984. this.setTarget(cameraTarget.position);
  10985. };
  10986. FollowCamera.prototype._checkInputs = function () {
  10987. _super.prototype._checkInputs.call(this);
  10988. this.follow(this.target);
  10989. };
  10990. FollowCamera.prototype.serialize = function () {
  10991. var serializationObject = _super.prototype.serialize.call(this);
  10992. serializationObject.radius = this.radius;
  10993. serializationObject.heightOffset = this.heightOffset;
  10994. serializationObject.rotationOffset = this.rotationOffset;
  10995. return serializationObject;
  10996. };
  10997. return FollowCamera;
  10998. })(BABYLON.TargetCamera);
  10999. BABYLON.FollowCamera = FollowCamera;
  11000. var ArcFollowCamera = (function (_super) {
  11001. __extends(ArcFollowCamera, _super);
  11002. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11003. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11004. this.alpha = alpha;
  11005. this.beta = beta;
  11006. this.radius = radius;
  11007. this.target = target;
  11008. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11009. this.follow();
  11010. }
  11011. ArcFollowCamera.prototype.follow = function () {
  11012. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11013. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11014. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11015. this.position = this.target.position.add(this._cartesianCoordinates);
  11016. this.setTarget(this.target.position);
  11017. };
  11018. ArcFollowCamera.prototype._checkInputs = function () {
  11019. _super.prototype._checkInputs.call(this);
  11020. this.follow();
  11021. };
  11022. ArcFollowCamera.prototype.serialize = function () {
  11023. var serializationObject = _super.prototype.serialize.call(this);
  11024. serializationObject.radius = this.radius;
  11025. return serializationObject;
  11026. };
  11027. return ArcFollowCamera;
  11028. })(BABYLON.TargetCamera);
  11029. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11030. })(BABYLON || (BABYLON = {}));
  11031. var BABYLON;
  11032. (function (BABYLON) {
  11033. // We're mainly based on the logic defined into the FreeCamera code
  11034. var TouchCamera = (function (_super) {
  11035. __extends(TouchCamera, _super);
  11036. function TouchCamera(name, position, scene) {
  11037. _super.call(this, name, position, scene);
  11038. this._offsetX = null;
  11039. this._offsetY = null;
  11040. this._pointerCount = 0;
  11041. this._pointerPressed = [];
  11042. this.angularSensibility = 200000.0;
  11043. this.moveSensibility = 500.0;
  11044. }
  11045. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11046. var _this = this;
  11047. var previousPosition;
  11048. if (this._attachedCanvas) {
  11049. return;
  11050. }
  11051. this._attachedCanvas = canvas;
  11052. if (this._onPointerDown === undefined) {
  11053. this._onPointerDown = function (evt) {
  11054. if (!noPreventDefault) {
  11055. evt.preventDefault();
  11056. }
  11057. _this._pointerPressed.push(evt.pointerId);
  11058. if (_this._pointerPressed.length !== 1) {
  11059. return;
  11060. }
  11061. previousPosition = {
  11062. x: evt.clientX,
  11063. y: evt.clientY
  11064. };
  11065. };
  11066. this._onPointerUp = function (evt) {
  11067. if (!noPreventDefault) {
  11068. evt.preventDefault();
  11069. }
  11070. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11071. if (index === -1) {
  11072. return;
  11073. }
  11074. _this._pointerPressed.splice(index, 1);
  11075. if (index != 0) {
  11076. return;
  11077. }
  11078. previousPosition = null;
  11079. _this._offsetX = null;
  11080. _this._offsetY = null;
  11081. };
  11082. this._onPointerMove = function (evt) {
  11083. if (!noPreventDefault) {
  11084. evt.preventDefault();
  11085. }
  11086. if (!previousPosition) {
  11087. return;
  11088. }
  11089. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11090. if (index != 0) {
  11091. return;
  11092. }
  11093. _this._offsetX = evt.clientX - previousPosition.x;
  11094. _this._offsetY = -(evt.clientY - previousPosition.y);
  11095. };
  11096. this._onLostFocus = function () {
  11097. _this._offsetX = null;
  11098. _this._offsetY = null;
  11099. };
  11100. }
  11101. canvas.addEventListener("pointerdown", this._onPointerDown);
  11102. canvas.addEventListener("pointerup", this._onPointerUp);
  11103. canvas.addEventListener("pointerout", this._onPointerUp);
  11104. canvas.addEventListener("pointermove", this._onPointerMove);
  11105. BABYLON.Tools.RegisterTopRootEvents([
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. };
  11109. TouchCamera.prototype.detachControl = function (canvas) {
  11110. if (this._attachedCanvas !== canvas) {
  11111. return;
  11112. }
  11113. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11114. canvas.removeEventListener("pointerup", this._onPointerUp);
  11115. canvas.removeEventListener("pointerout", this._onPointerUp);
  11116. canvas.removeEventListener("pointermove", this._onPointerMove);
  11117. BABYLON.Tools.UnregisterTopRootEvents([
  11118. { name: "blur", handler: this._onLostFocus }
  11119. ]);
  11120. this._attachedCanvas = null;
  11121. };
  11122. TouchCamera.prototype._checkInputs = function () {
  11123. if (this._offsetX) {
  11124. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11125. if (this._pointerPressed.length > 1) {
  11126. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11127. }
  11128. else {
  11129. var speed = this._computeLocalCameraSpeed();
  11130. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11131. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11132. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11133. }
  11134. }
  11135. _super.prototype._checkInputs.call(this);
  11136. };
  11137. return TouchCamera;
  11138. })(BABYLON.FreeCamera);
  11139. BABYLON.TouchCamera = TouchCamera;
  11140. })(BABYLON || (BABYLON = {}));
  11141. var BABYLON;
  11142. (function (BABYLON) {
  11143. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11144. var ArcRotateCamera = (function (_super) {
  11145. __extends(ArcRotateCamera, _super);
  11146. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11147. var _this = this;
  11148. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11149. this.alpha = alpha;
  11150. this.beta = beta;
  11151. this.radius = radius;
  11152. this.target = target;
  11153. this.inertialAlphaOffset = 0;
  11154. this.inertialBetaOffset = 0;
  11155. this.inertialRadiusOffset = 0;
  11156. this.lowerAlphaLimit = null;
  11157. this.upperAlphaLimit = null;
  11158. this.lowerBetaLimit = 0.01;
  11159. this.upperBetaLimit = Math.PI;
  11160. this.lowerRadiusLimit = null;
  11161. this.upperRadiusLimit = null;
  11162. this.angularSensibilityX = 1000.0;
  11163. this.angularSensibilityY = 1000.0;
  11164. this.wheelPrecision = 3.0;
  11165. this.pinchPrecision = 2.0;
  11166. this.panningSensibility = 50.0;
  11167. this.inertialPanningX = 0;
  11168. this.inertialPanningY = 0;
  11169. this.keysUp = [38];
  11170. this.keysDown = [40];
  11171. this.keysLeft = [37];
  11172. this.keysRight = [39];
  11173. this.zoomOnFactor = 1;
  11174. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11175. this.pinchInwards = true;
  11176. this.allowUpsideDown = true;
  11177. this._keys = [];
  11178. this._viewMatrix = new BABYLON.Matrix();
  11179. this._isRightClick = false;
  11180. this._isCtrlPushed = false;
  11181. this.checkCollisions = false;
  11182. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11183. this._collider = new BABYLON.Collider();
  11184. this._previousPosition = BABYLON.Vector3.Zero();
  11185. this._collisionVelocity = BABYLON.Vector3.Zero();
  11186. this._newPosition = BABYLON.Vector3.Zero();
  11187. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11188. if (collidedMesh === void 0) { collidedMesh = null; }
  11189. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11190. newPosition.multiplyInPlace(_this._collider.radius);
  11191. }
  11192. if (!collidedMesh) {
  11193. _this._previousPosition.copyFrom(_this.position);
  11194. }
  11195. else {
  11196. _this.setPosition(newPosition);
  11197. if (_this.onCollide) {
  11198. _this.onCollide(collidedMesh);
  11199. }
  11200. }
  11201. // Recompute because of constraints
  11202. var cosa = Math.cos(_this.alpha);
  11203. var sina = Math.sin(_this.alpha);
  11204. var cosb = Math.cos(_this.beta);
  11205. var sinb = Math.sin(_this.beta);
  11206. var target = _this._getTargetPosition();
  11207. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11208. _this.position.copyFrom(_this._newPosition);
  11209. var up = _this.upVector;
  11210. if (_this.allowUpsideDown && _this.beta < 0) {
  11211. up = up.clone();
  11212. up = up.negate();
  11213. }
  11214. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11215. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11216. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11217. _this._collisionTriggered = false;
  11218. };
  11219. if (!this.target) {
  11220. this.target = BABYLON.Vector3.Zero();
  11221. }
  11222. this.getViewMatrix();
  11223. }
  11224. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11225. //deprecated angularSensibility support
  11226. get: function () {
  11227. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11228. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11229. },
  11230. //deprecated angularSensibility support
  11231. set: function (value) {
  11232. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11233. this.angularSensibilityX = value;
  11234. this.angularSensibilityY = value;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. ArcRotateCamera.prototype._getTargetPosition = function () {
  11240. return this.target.position || this.target;
  11241. };
  11242. // Cache
  11243. ArcRotateCamera.prototype._initCache = function () {
  11244. _super.prototype._initCache.call(this);
  11245. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11246. this._cache.alpha = undefined;
  11247. this._cache.beta = undefined;
  11248. this._cache.radius = undefined;
  11249. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11250. };
  11251. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11252. if (!ignoreParentClass) {
  11253. _super.prototype._updateCache.call(this);
  11254. }
  11255. this._cache.target.copyFrom(this._getTargetPosition());
  11256. this._cache.alpha = this.alpha;
  11257. this._cache.beta = this.beta;
  11258. this._cache.radius = this.radius;
  11259. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11260. };
  11261. // Synchronized
  11262. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11263. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11264. return false;
  11265. return this._cache.target.equals(this._getTargetPosition())
  11266. && this._cache.alpha === this.alpha
  11267. && this._cache.beta === this.beta
  11268. && this._cache.radius === this.radius
  11269. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11270. };
  11271. // Methods
  11272. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11273. var _this = this;
  11274. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11275. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11276. var previousPinchDistance = 0;
  11277. var pointers = new BABYLON.SmartCollection();
  11278. if (this._attachedElement) {
  11279. return;
  11280. }
  11281. this._attachedElement = element;
  11282. var engine = this.getEngine();
  11283. if (this._onPointerDown === undefined) {
  11284. this._onPointerDown = function (evt) {
  11285. // Manage panning with right click
  11286. _this._isRightClick = evt.button === 2;
  11287. // manage pointers
  11288. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11289. cacheSoloPointer = pointers.item(evt.pointerId);
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onPointerUp = function (evt) {
  11295. cacheSoloPointer = null;
  11296. previousPinchDistance = 0;
  11297. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11298. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11299. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11300. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11301. pointers.empty();
  11302. if (!noPreventDefault) {
  11303. evt.preventDefault();
  11304. }
  11305. };
  11306. this._onContextMenu = function (evt) {
  11307. evt.preventDefault();
  11308. };
  11309. this._onPointerMove = function (evt) {
  11310. if (!noPreventDefault) {
  11311. evt.preventDefault();
  11312. }
  11313. switch (pointers.count) {
  11314. case 1:
  11315. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11316. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11317. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11318. }
  11319. else {
  11320. var offsetX = evt.clientX - cacheSoloPointer.x;
  11321. var offsetY = evt.clientY - cacheSoloPointer.y;
  11322. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11323. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11324. }
  11325. cacheSoloPointer.x = evt.clientX;
  11326. cacheSoloPointer.y = evt.clientY;
  11327. break;
  11328. case 2:
  11329. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11330. pointers.item(evt.pointerId).x = evt.clientX;
  11331. pointers.item(evt.pointerId).y = evt.clientY;
  11332. var direction = _this.pinchInwards ? 1 : -1;
  11333. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11334. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11335. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11336. if (previousPinchDistance === 0) {
  11337. previousPinchDistance = pinchSquaredDistance;
  11338. return;
  11339. }
  11340. if (pinchSquaredDistance !== previousPinchDistance) {
  11341. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11342. previousPinchDistance = pinchSquaredDistance;
  11343. }
  11344. break;
  11345. default:
  11346. if (pointers.item(evt.pointerId)) {
  11347. pointers.item(evt.pointerId).x = evt.clientX;
  11348. pointers.item(evt.pointerId).y = evt.clientY;
  11349. }
  11350. }
  11351. };
  11352. this._onMouseMove = function (evt) {
  11353. if (!engine.isPointerLock) {
  11354. return;
  11355. }
  11356. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11357. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11358. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11359. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11360. if (!noPreventDefault) {
  11361. evt.preventDefault();
  11362. }
  11363. };
  11364. this._wheel = function (event) {
  11365. var delta = 0;
  11366. if (event.wheelDelta) {
  11367. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11368. }
  11369. else if (event.detail) {
  11370. delta = -event.detail / _this.wheelPrecision;
  11371. }
  11372. if (delta)
  11373. _this.inertialRadiusOffset += delta;
  11374. if (event.preventDefault) {
  11375. if (!noPreventDefault) {
  11376. event.preventDefault();
  11377. }
  11378. }
  11379. };
  11380. this._onKeyDown = function (evt) {
  11381. _this._isCtrlPushed = evt.ctrlKey;
  11382. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11383. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11384. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11385. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11386. var index = _this._keys.indexOf(evt.keyCode);
  11387. if (index === -1) {
  11388. _this._keys.push(evt.keyCode);
  11389. }
  11390. if (evt.preventDefault) {
  11391. if (!noPreventDefault) {
  11392. evt.preventDefault();
  11393. }
  11394. }
  11395. }
  11396. };
  11397. this._onKeyUp = function (evt) {
  11398. _this._isCtrlPushed = evt.ctrlKey;
  11399. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11400. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11401. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11402. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11403. var index = _this._keys.indexOf(evt.keyCode);
  11404. if (index >= 0) {
  11405. _this._keys.splice(index, 1);
  11406. }
  11407. if (evt.preventDefault) {
  11408. if (!noPreventDefault) {
  11409. evt.preventDefault();
  11410. }
  11411. }
  11412. }
  11413. };
  11414. this._onLostFocus = function () {
  11415. _this._keys = [];
  11416. pointers.empty();
  11417. previousPinchDistance = 0;
  11418. cacheSoloPointer = null;
  11419. };
  11420. this._onGestureStart = function (e) {
  11421. if (window.MSGesture === undefined) {
  11422. return;
  11423. }
  11424. if (!_this._MSGestureHandler) {
  11425. _this._MSGestureHandler = new MSGesture();
  11426. _this._MSGestureHandler.target = element;
  11427. }
  11428. _this._MSGestureHandler.addPointer(e.pointerId);
  11429. };
  11430. this._onGesture = function (e) {
  11431. _this.radius *= e.scale;
  11432. if (e.preventDefault) {
  11433. if (!noPreventDefault) {
  11434. e.stopPropagation();
  11435. e.preventDefault();
  11436. }
  11437. }
  11438. };
  11439. this._reset = function () {
  11440. _this._keys = [];
  11441. _this.inertialAlphaOffset = 0;
  11442. _this.inertialBetaOffset = 0;
  11443. _this.inertialRadiusOffset = 0;
  11444. pointers.empty();
  11445. previousPinchDistance = 0;
  11446. cacheSoloPointer = null;
  11447. };
  11448. }
  11449. if (!useCtrlForPanning) {
  11450. element.addEventListener("contextmenu", this._onContextMenu, false);
  11451. }
  11452. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11453. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11454. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11455. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11456. element.addEventListener("mousemove", this._onMouseMove, false);
  11457. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11458. element.addEventListener("MSGestureChange", this._onGesture, false);
  11459. element.addEventListener('mousewheel', this._wheel, false);
  11460. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11461. BABYLON.Tools.RegisterTopRootEvents([
  11462. { name: "keydown", handler: this._onKeyDown },
  11463. { name: "keyup", handler: this._onKeyUp },
  11464. { name: "blur", handler: this._onLostFocus }
  11465. ]);
  11466. };
  11467. ArcRotateCamera.prototype.detachControl = function (element) {
  11468. if (this._attachedElement !== element) {
  11469. return;
  11470. }
  11471. element.removeEventListener("contextmenu", this._onContextMenu);
  11472. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11473. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11474. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11475. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11476. element.removeEventListener("mousemove", this._onMouseMove);
  11477. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11478. element.removeEventListener("MSGestureChange", this._onGesture);
  11479. element.removeEventListener('mousewheel', this._wheel);
  11480. element.removeEventListener('DOMMouseScroll', this._wheel);
  11481. BABYLON.Tools.UnregisterTopRootEvents([
  11482. { name: "keydown", handler: this._onKeyDown },
  11483. { name: "keyup", handler: this._onKeyUp },
  11484. { name: "blur", handler: this._onLostFocus }
  11485. ]);
  11486. this._MSGestureHandler = null;
  11487. this._attachedElement = null;
  11488. if (this._reset) {
  11489. this._reset();
  11490. }
  11491. };
  11492. ArcRotateCamera.prototype._checkInputs = function () {
  11493. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11494. if (this._collisionTriggered) {
  11495. return;
  11496. }
  11497. // Keyboard
  11498. for (var index = 0; index < this._keys.length; index++) {
  11499. var keyCode = this._keys[index];
  11500. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11501. this.inertialAlphaOffset -= 0.01;
  11502. }
  11503. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11504. this.inertialBetaOffset -= 0.01;
  11505. }
  11506. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11507. this.inertialAlphaOffset += 0.01;
  11508. }
  11509. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11510. this.inertialBetaOffset += 0.01;
  11511. }
  11512. }
  11513. // Inertia
  11514. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11515. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11516. this.beta += this.inertialBetaOffset;
  11517. this.radius -= this.inertialRadiusOffset;
  11518. this.inertialAlphaOffset *= this.inertia;
  11519. this.inertialBetaOffset *= this.inertia;
  11520. this.inertialRadiusOffset *= this.inertia;
  11521. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11522. this.inertialAlphaOffset = 0;
  11523. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11524. this.inertialBetaOffset = 0;
  11525. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11526. this.inertialRadiusOffset = 0;
  11527. }
  11528. // Panning inertia
  11529. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11530. if (!this._localDirection) {
  11531. this._localDirection = BABYLON.Vector3.Zero();
  11532. this._transformedDirection = BABYLON.Vector3.Zero();
  11533. }
  11534. this.inertialPanningX *= this.inertia;
  11535. this.inertialPanningY *= this.inertia;
  11536. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11537. this.inertialPanningX = 0;
  11538. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11539. this.inertialPanningY = 0;
  11540. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11541. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11542. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11543. this.target.addInPlace(this._transformedDirection);
  11544. }
  11545. // Limits
  11546. this._checkLimits();
  11547. _super.prototype._checkInputs.call(this);
  11548. };
  11549. ArcRotateCamera.prototype._checkLimits = function () {
  11550. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11551. if (this.allowUpsideDown && this.beta > Math.PI) {
  11552. this.beta = this.beta - (2 * Math.PI);
  11553. }
  11554. }
  11555. else {
  11556. if (this.beta < this.lowerBetaLimit) {
  11557. this.beta = this.lowerBetaLimit;
  11558. }
  11559. }
  11560. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11561. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11562. this.beta = this.beta + (2 * Math.PI);
  11563. }
  11564. }
  11565. else {
  11566. if (this.beta > this.upperBetaLimit) {
  11567. this.beta = this.upperBetaLimit;
  11568. }
  11569. }
  11570. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11571. this.alpha = this.lowerAlphaLimit;
  11572. }
  11573. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11574. this.alpha = this.upperAlphaLimit;
  11575. }
  11576. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11577. this.radius = this.lowerRadiusLimit;
  11578. }
  11579. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11580. this.radius = this.upperRadiusLimit;
  11581. }
  11582. };
  11583. ArcRotateCamera.prototype.setPosition = function (position) {
  11584. if (this.position.equals(position)) {
  11585. return;
  11586. }
  11587. var radiusv3 = position.subtract(this._getTargetPosition());
  11588. this.radius = radiusv3.length();
  11589. // Alpha
  11590. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11591. if (radiusv3.z < 0) {
  11592. this.alpha = 2 * Math.PI - this.alpha;
  11593. }
  11594. // Beta
  11595. this.beta = Math.acos(radiusv3.y / this.radius);
  11596. this._checkLimits();
  11597. };
  11598. ArcRotateCamera.prototype.setTarget = function (target) {
  11599. this.target = target;
  11600. };
  11601. ArcRotateCamera.prototype._getViewMatrix = function () {
  11602. // Compute
  11603. var cosa = Math.cos(this.alpha);
  11604. var sina = Math.sin(this.alpha);
  11605. var cosb = Math.cos(this.beta);
  11606. var sinb = Math.sin(this.beta);
  11607. var target = this._getTargetPosition();
  11608. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11609. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11610. this._collider.radius = this.collisionRadius;
  11611. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11612. this._collisionTriggered = true;
  11613. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11614. }
  11615. else {
  11616. this.position.copyFrom(this._newPosition);
  11617. var up = this.upVector;
  11618. if (this.allowUpsideDown && this.beta < 0) {
  11619. up = up.clone();
  11620. up = up.negate();
  11621. }
  11622. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11623. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11624. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11625. }
  11626. return this._viewMatrix;
  11627. };
  11628. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11629. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11630. meshes = meshes || this.getScene().meshes;
  11631. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11632. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11633. this.radius = distance * this.zoomOnFactor;
  11634. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11635. };
  11636. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11637. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11638. var meshesOrMinMaxVector;
  11639. var distance;
  11640. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11641. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11642. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11643. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11644. }
  11645. else {
  11646. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11647. distance = meshesOrMinMaxVectorAndDistance.distance;
  11648. }
  11649. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11650. if (!doNotUpdateMaxZ) {
  11651. this.maxZ = distance * 2;
  11652. }
  11653. };
  11654. /**
  11655. * @override
  11656. * Override Camera.createRigCamera
  11657. */
  11658. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11659. switch (this.cameraRigMode) {
  11660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11663. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11664. case BABYLON.Camera.RIG_MODE_VR:
  11665. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11666. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11667. }
  11668. return null;
  11669. };
  11670. /**
  11671. * @override
  11672. * Override Camera._updateRigCameras
  11673. */
  11674. ArcRotateCamera.prototype._updateRigCameras = function () {
  11675. switch (this.cameraRigMode) {
  11676. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11677. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11678. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11680. case BABYLON.Camera.RIG_MODE_VR:
  11681. var camLeft = this._rigCameras[0];
  11682. var camRight = this._rigCameras[1];
  11683. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11684. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11685. camLeft.beta = camRight.beta = this.beta;
  11686. camLeft.radius = camRight.radius = this.radius;
  11687. break;
  11688. }
  11689. _super.prototype._updateRigCameras.call(this);
  11690. };
  11691. ArcRotateCamera.prototype.serialize = function () {
  11692. var serializationObject = _super.prototype.serialize.call(this);
  11693. if (this.target instanceof BABYLON.Vector3) {
  11694. serializationObject.target = this.target.asArray();
  11695. }
  11696. if (this.target && this.target.id) {
  11697. serializationObject.lockedTargetId = this.target.id;
  11698. }
  11699. serializationObject.checkCollisions = this.checkCollisions;
  11700. serializationObject.alpha = this.alpha;
  11701. serializationObject.beta = this.beta;
  11702. serializationObject.radius = this.radius;
  11703. return serializationObject;
  11704. };
  11705. return ArcRotateCamera;
  11706. })(BABYLON.TargetCamera);
  11707. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11708. })(BABYLON || (BABYLON = {}));
  11709. var BABYLON;
  11710. (function (BABYLON) {
  11711. var RenderingManager = (function () {
  11712. function RenderingManager(scene) {
  11713. this._renderingGroups = new Array();
  11714. this._scene = scene;
  11715. }
  11716. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11717. if (this._scene._activeParticleSystems.length === 0) {
  11718. return;
  11719. }
  11720. // Particles
  11721. var activeCamera = this._scene.activeCamera;
  11722. var beforeParticlesDate = BABYLON.Tools.Now;
  11723. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11724. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11725. if (particleSystem.renderingGroupId !== index) {
  11726. continue;
  11727. }
  11728. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11729. continue;
  11730. }
  11731. this._clearDepthBuffer();
  11732. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11733. this._scene._activeParticles += particleSystem.render();
  11734. }
  11735. }
  11736. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11737. };
  11738. RenderingManager.prototype._renderSprites = function (index) {
  11739. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11740. return;
  11741. }
  11742. // Sprites
  11743. var activeCamera = this._scene.activeCamera;
  11744. var beforeSpritessDate = BABYLON.Tools.Now;
  11745. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11746. var spriteManager = this._scene.spriteManagers[id];
  11747. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11748. this._clearDepthBuffer();
  11749. spriteManager.render();
  11750. }
  11751. }
  11752. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11753. };
  11754. RenderingManager.prototype._clearDepthBuffer = function () {
  11755. if (this._depthBufferAlreadyCleaned) {
  11756. return;
  11757. }
  11758. this._scene.getEngine().clear(0, false, true);
  11759. this._depthBufferAlreadyCleaned = true;
  11760. };
  11761. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11762. if (this._currentRenderSprites) {
  11763. this._renderSprites(this._currentIndex);
  11764. }
  11765. if (this._currentRenderParticles) {
  11766. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11767. }
  11768. };
  11769. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11770. this._currentActiveMeshes = activeMeshes;
  11771. this._currentRenderParticles = renderParticles;
  11772. this._currentRenderSprites = renderSprites;
  11773. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11774. this._depthBufferAlreadyCleaned = index == 0;
  11775. var renderingGroup = this._renderingGroups[index];
  11776. var needToStepBack = false;
  11777. this._currentIndex = index;
  11778. if (renderingGroup) {
  11779. this._clearDepthBuffer();
  11780. if (!renderingGroup.onBeforeTransparentRendering) {
  11781. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11782. }
  11783. if (!renderingGroup.render(customRenderFunction)) {
  11784. this._renderingGroups.splice(index, 1);
  11785. needToStepBack = true;
  11786. this._renderSpritesAndParticles();
  11787. }
  11788. }
  11789. else {
  11790. this._renderSpritesAndParticles();
  11791. }
  11792. if (needToStepBack) {
  11793. index--;
  11794. }
  11795. }
  11796. };
  11797. RenderingManager.prototype.reset = function () {
  11798. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11799. if (renderingGroup) {
  11800. renderingGroup.prepare();
  11801. }
  11802. });
  11803. };
  11804. RenderingManager.prototype.dispatch = function (subMesh) {
  11805. var mesh = subMesh.getMesh();
  11806. var renderingGroupId = mesh.renderingGroupId || 0;
  11807. if (!this._renderingGroups[renderingGroupId]) {
  11808. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11809. }
  11810. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11811. };
  11812. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11813. return RenderingManager;
  11814. })();
  11815. BABYLON.RenderingManager = RenderingManager;
  11816. })(BABYLON || (BABYLON = {}));
  11817. var BABYLON;
  11818. (function (BABYLON) {
  11819. var RenderingGroup = (function () {
  11820. function RenderingGroup(index, scene) {
  11821. this.index = index;
  11822. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11823. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11824. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11825. this._scene = scene;
  11826. }
  11827. RenderingGroup.prototype.render = function (customRenderFunction) {
  11828. if (customRenderFunction) {
  11829. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11830. return true;
  11831. }
  11832. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11833. if (this.onBeforeTransparentRendering) {
  11834. this.onBeforeTransparentRendering();
  11835. }
  11836. return false;
  11837. }
  11838. var engine = this._scene.getEngine();
  11839. // Opaque
  11840. var subIndex;
  11841. var submesh;
  11842. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11843. submesh = this._opaqueSubMeshes.data[subIndex];
  11844. submesh.render(false);
  11845. }
  11846. // Alpha test
  11847. engine.setAlphaTesting(true);
  11848. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11849. submesh = this._alphaTestSubMeshes.data[subIndex];
  11850. submesh.render(false);
  11851. }
  11852. engine.setAlphaTesting(false);
  11853. if (this.onBeforeTransparentRendering) {
  11854. this.onBeforeTransparentRendering();
  11855. }
  11856. // Transparent
  11857. if (this._transparentSubMeshes.length) {
  11858. // Sorting
  11859. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11860. submesh = this._transparentSubMeshes.data[subIndex];
  11861. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11862. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11863. }
  11864. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11865. sortedArray.sort(function (a, b) {
  11866. // Alpha index first
  11867. if (a._alphaIndex > b._alphaIndex) {
  11868. return 1;
  11869. }
  11870. if (a._alphaIndex < b._alphaIndex) {
  11871. return -1;
  11872. }
  11873. // Then distance to camera
  11874. if (a._distanceToCamera < b._distanceToCamera) {
  11875. return 1;
  11876. }
  11877. if (a._distanceToCamera > b._distanceToCamera) {
  11878. return -1;
  11879. }
  11880. return 0;
  11881. });
  11882. // Rendering
  11883. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11884. submesh = sortedArray[subIndex];
  11885. submesh.render(true);
  11886. }
  11887. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11888. }
  11889. return true;
  11890. };
  11891. RenderingGroup.prototype.prepare = function () {
  11892. this._opaqueSubMeshes.reset();
  11893. this._transparentSubMeshes.reset();
  11894. this._alphaTestSubMeshes.reset();
  11895. };
  11896. RenderingGroup.prototype.dispatch = function (subMesh) {
  11897. var material = subMesh.getMaterial();
  11898. var mesh = subMesh.getMesh();
  11899. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11900. this._transparentSubMeshes.push(subMesh);
  11901. }
  11902. else if (material.needAlphaTesting()) {
  11903. this._alphaTestSubMeshes.push(subMesh);
  11904. }
  11905. else {
  11906. this._opaqueSubMeshes.push(subMesh); // Opaque
  11907. }
  11908. };
  11909. return RenderingGroup;
  11910. })();
  11911. BABYLON.RenderingGroup = RenderingGroup;
  11912. })(BABYLON || (BABYLON = {}));
  11913. var BABYLON;
  11914. (function (BABYLON) {
  11915. /**
  11916. * Represents a scene to be rendered by the engine.
  11917. * @see http://doc.babylonjs.com/page.php?p=21911
  11918. */
  11919. var Scene = (function () {
  11920. /**
  11921. * @constructor
  11922. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11923. */
  11924. function Scene(engine) {
  11925. // Members
  11926. this.autoClear = true;
  11927. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11928. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11929. this.forceWireframe = false;
  11930. this.forcePointsCloud = false;
  11931. this.forceShowBoundingBoxes = false;
  11932. this.animationsEnabled = true;
  11933. this.constantlyUpdateMeshUnderPointer = false;
  11934. 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
  11935. // Fog
  11936. /**
  11937. * is fog enabled on this scene.
  11938. * @type {boolean}
  11939. */
  11940. this.fogEnabled = true;
  11941. this.fogMode = Scene.FOGMODE_NONE;
  11942. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11943. this.fogDensity = 0.1;
  11944. this.fogStart = 0;
  11945. this.fogEnd = 1000.0;
  11946. // Lights
  11947. /**
  11948. * is shadow enabled on this scene.
  11949. * @type {boolean}
  11950. */
  11951. this.shadowsEnabled = true;
  11952. /**
  11953. * is light enabled on this scene.
  11954. * @type {boolean}
  11955. */
  11956. this.lightsEnabled = true;
  11957. /**
  11958. * All of the lights added to this scene.
  11959. * @see BABYLON.Light
  11960. * @type {BABYLON.Light[]}
  11961. */
  11962. this.lights = new Array();
  11963. // Cameras
  11964. /**
  11965. * All of the cameras added to this scene.
  11966. * @see BABYLON.Camera
  11967. * @type {BABYLON.Camera[]}
  11968. */
  11969. this.cameras = new Array();
  11970. this.activeCameras = new Array();
  11971. // Meshes
  11972. /**
  11973. * All of the (abstract) meshes added to this scene.
  11974. * @see BABYLON.AbstractMesh
  11975. * @type {BABYLON.AbstractMesh[]}
  11976. */
  11977. this.meshes = new Array();
  11978. // Geometries
  11979. this._geometries = new Array();
  11980. this.materials = new Array();
  11981. this.multiMaterials = new Array();
  11982. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11983. // Textures
  11984. this.texturesEnabled = true;
  11985. this.textures = new Array();
  11986. // Particles
  11987. this.particlesEnabled = true;
  11988. this.particleSystems = new Array();
  11989. // Sprites
  11990. this.spritesEnabled = true;
  11991. this.spriteManagers = new Array();
  11992. // Layers
  11993. this.layers = new Array();
  11994. // Skeletons
  11995. this.skeletonsEnabled = true;
  11996. this.skeletons = new Array();
  11997. // Lens flares
  11998. this.lensFlaresEnabled = true;
  11999. this.lensFlareSystems = new Array();
  12000. // Collisions
  12001. this.collisionsEnabled = true;
  12002. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12003. // Postprocesses
  12004. this.postProcessesEnabled = true;
  12005. // Customs render targets
  12006. this.renderTargetsEnabled = true;
  12007. this.dumpNextRenderTargets = false;
  12008. this.customRenderTargets = new Array();
  12009. // Imported meshes
  12010. this.importedMeshesFiles = new Array();
  12011. // Probes
  12012. this.probesEnabled = true;
  12013. this.reflectionProbes = new Array();
  12014. this._actionManagers = new Array();
  12015. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12016. // Procedural textures
  12017. this.proceduralTexturesEnabled = true;
  12018. this._proceduralTextures = new Array();
  12019. this.soundTracks = new Array();
  12020. this._audioEnabled = true;
  12021. this._headphone = false;
  12022. this._totalVertices = 0;
  12023. this._activeIndices = 0;
  12024. this._activeParticles = 0;
  12025. this._lastFrameDuration = 0;
  12026. this._evaluateActiveMeshesDuration = 0;
  12027. this._renderTargetsDuration = 0;
  12028. this._particlesDuration = 0;
  12029. this._renderDuration = 0;
  12030. this._spritesDuration = 0;
  12031. this._animationRatio = 0;
  12032. this._renderId = 0;
  12033. this._executeWhenReadyTimeoutId = -1;
  12034. this._toBeDisposed = new BABYLON.SmartArray(256);
  12035. this._onReadyCallbacks = new Array();
  12036. this._pendingData = []; //ANY
  12037. this._onBeforeRenderCallbacks = new Array();
  12038. this._onAfterRenderCallbacks = new Array();
  12039. this._activeMeshes = new BABYLON.SmartArray(256);
  12040. this._processedMaterials = new BABYLON.SmartArray(256);
  12041. this._renderTargets = new BABYLON.SmartArray(256);
  12042. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12043. this._activeSkeletons = new BABYLON.SmartArray(32);
  12044. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12045. this._activeBones = 0;
  12046. this._activeAnimatables = new Array();
  12047. this._transformMatrix = BABYLON.Matrix.Zero();
  12048. this._edgesRenderers = new BABYLON.SmartArray(16);
  12049. this._uniqueIdCounter = 0;
  12050. this._engine = engine;
  12051. engine.scenes.push(this);
  12052. this._renderingManager = new BABYLON.RenderingManager(this);
  12053. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12054. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12055. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12056. if (BABYLON.OutlineRenderer) {
  12057. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12058. }
  12059. this.attachControl();
  12060. this._debugLayer = new BABYLON.DebugLayer(this);
  12061. if (BABYLON.SoundTrack) {
  12062. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12063. }
  12064. //simplification queue
  12065. if (BABYLON.SimplificationQueue) {
  12066. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12067. }
  12068. //collision coordinator initialization. For now legacy per default.
  12069. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12070. }
  12071. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12072. get: function () {
  12073. return Scene._FOGMODE_NONE;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12079. get: function () {
  12080. return Scene._FOGMODE_EXP;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12086. get: function () {
  12087. return Scene._FOGMODE_EXP2;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12093. get: function () {
  12094. return Scene._FOGMODE_LINEAR;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(Scene.prototype, "debugLayer", {
  12100. // Properties
  12101. get: function () {
  12102. return this._debugLayer;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12108. get: function () {
  12109. return this._workerCollisions;
  12110. },
  12111. set: function (enabled) {
  12112. enabled = (enabled && !!Worker);
  12113. this._workerCollisions = enabled;
  12114. if (this.collisionCoordinator) {
  12115. this.collisionCoordinator.destroy();
  12116. }
  12117. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12118. this.collisionCoordinator.init(this);
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12124. get: function () {
  12125. return this._selectionOctree;
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12131. /**
  12132. * The mesh that is currently under the pointer.
  12133. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12134. */
  12135. get: function () {
  12136. return this._meshUnderPointer;
  12137. },
  12138. enumerable: true,
  12139. configurable: true
  12140. });
  12141. Object.defineProperty(Scene.prototype, "pointerX", {
  12142. /**
  12143. * Current on-screen X position of the pointer
  12144. * @return {number} X position of the pointer
  12145. */
  12146. get: function () {
  12147. return this._pointerX;
  12148. },
  12149. enumerable: true,
  12150. configurable: true
  12151. });
  12152. Object.defineProperty(Scene.prototype, "pointerY", {
  12153. /**
  12154. * Current on-screen Y position of the pointer
  12155. * @return {number} Y position of the pointer
  12156. */
  12157. get: function () {
  12158. return this._pointerY;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Scene.prototype.getCachedMaterial = function () {
  12164. return this._cachedMaterial;
  12165. };
  12166. Scene.prototype.getBoundingBoxRenderer = function () {
  12167. return this._boundingBoxRenderer;
  12168. };
  12169. Scene.prototype.getOutlineRenderer = function () {
  12170. return this._outlineRenderer;
  12171. };
  12172. Scene.prototype.getEngine = function () {
  12173. return this._engine;
  12174. };
  12175. Scene.prototype.getTotalVertices = function () {
  12176. return this._totalVertices;
  12177. };
  12178. Scene.prototype.getActiveIndices = function () {
  12179. return this._activeIndices;
  12180. };
  12181. Scene.prototype.getActiveParticles = function () {
  12182. return this._activeParticles;
  12183. };
  12184. Scene.prototype.getActiveBones = function () {
  12185. return this._activeBones;
  12186. };
  12187. // Stats
  12188. Scene.prototype.getLastFrameDuration = function () {
  12189. return this._lastFrameDuration;
  12190. };
  12191. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12192. return this._evaluateActiveMeshesDuration;
  12193. };
  12194. Scene.prototype.getActiveMeshes = function () {
  12195. return this._activeMeshes;
  12196. };
  12197. Scene.prototype.getRenderTargetsDuration = function () {
  12198. return this._renderTargetsDuration;
  12199. };
  12200. Scene.prototype.getRenderDuration = function () {
  12201. return this._renderDuration;
  12202. };
  12203. Scene.prototype.getParticlesDuration = function () {
  12204. return this._particlesDuration;
  12205. };
  12206. Scene.prototype.getSpritesDuration = function () {
  12207. return this._spritesDuration;
  12208. };
  12209. Scene.prototype.getAnimationRatio = function () {
  12210. return this._animationRatio;
  12211. };
  12212. Scene.prototype.getRenderId = function () {
  12213. return this._renderId;
  12214. };
  12215. Scene.prototype.incrementRenderId = function () {
  12216. this._renderId++;
  12217. };
  12218. Scene.prototype._updatePointerPosition = function (evt) {
  12219. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12220. this._pointerX = evt.clientX - canvasRect.left;
  12221. this._pointerY = evt.clientY - canvasRect.top;
  12222. if (this.cameraToUseForPointers) {
  12223. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12224. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12225. }
  12226. };
  12227. // Pointers handling
  12228. Scene.prototype.attachControl = function () {
  12229. var _this = this;
  12230. var spritePredicate = function (sprite) {
  12231. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12232. };
  12233. this._onPointerMove = function (evt) {
  12234. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12235. return;
  12236. }
  12237. var canvas = _this._engine.getRenderingCanvas();
  12238. _this._updatePointerPosition(evt);
  12239. // Meshes
  12240. 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);
  12241. if (pickResult.hit && pickResult.pickedMesh) {
  12242. _this._meshUnderPointer = pickResult.pickedMesh;
  12243. _this.setPointerOverMesh(pickResult.pickedMesh);
  12244. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12245. canvas.style.cursor = "pointer";
  12246. }
  12247. else {
  12248. canvas.style.cursor = "";
  12249. }
  12250. }
  12251. else {
  12252. // Sprites
  12253. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12254. if (pickResult.hit && pickResult.pickedSprite) {
  12255. canvas.style.cursor = "pointer";
  12256. }
  12257. else {
  12258. // Restore pointer
  12259. _this.setPointerOverMesh(null);
  12260. canvas.style.cursor = "";
  12261. _this._meshUnderPointer = null;
  12262. }
  12263. }
  12264. if (_this.onPointerMove) {
  12265. _this.onPointerMove(evt, pickResult);
  12266. }
  12267. };
  12268. this._onPointerDown = function (evt) {
  12269. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12270. return;
  12271. }
  12272. _this._updatePointerPosition(evt);
  12273. var predicate = null;
  12274. // Meshes
  12275. if (!_this.onPointerDown) {
  12276. predicate = function (mesh) {
  12277. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12278. };
  12279. }
  12280. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12281. if (pickResult.hit && pickResult.pickedMesh) {
  12282. if (pickResult.pickedMesh.actionManager) {
  12283. switch (evt.button) {
  12284. case 0:
  12285. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12286. break;
  12287. case 1:
  12288. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12289. break;
  12290. case 2:
  12291. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12292. break;
  12293. }
  12294. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12295. }
  12296. }
  12297. if (_this.onPointerDown) {
  12298. _this.onPointerDown(evt, pickResult);
  12299. }
  12300. // Sprites
  12301. if (_this.spriteManagers.length > 0) {
  12302. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12303. if (pickResult.hit && pickResult.pickedSprite) {
  12304. if (pickResult.pickedSprite.actionManager) {
  12305. switch (evt.button) {
  12306. case 0:
  12307. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12308. break;
  12309. case 1:
  12310. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12311. break;
  12312. case 2:
  12313. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12314. break;
  12315. }
  12316. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12317. }
  12318. }
  12319. }
  12320. };
  12321. this._onPointerUp = function (evt) {
  12322. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12323. return;
  12324. }
  12325. var predicate = null;
  12326. _this._updatePointerPosition(evt);
  12327. if (!_this.onPointerUp) {
  12328. predicate = function (mesh) {
  12329. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12330. };
  12331. }
  12332. // Meshes
  12333. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12334. if (pickResult.hit && pickResult.pickedMesh) {
  12335. if (pickResult.pickedMesh.actionManager) {
  12336. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12337. }
  12338. }
  12339. if (_this.onPointerUp) {
  12340. _this.onPointerUp(evt, pickResult);
  12341. }
  12342. // Sprites
  12343. if (_this.spriteManagers.length > 0) {
  12344. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12345. if (pickResult.hit && pickResult.pickedSprite) {
  12346. if (pickResult.pickedSprite.actionManager) {
  12347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12348. }
  12349. }
  12350. }
  12351. };
  12352. this._onKeyDown = function (evt) {
  12353. if (_this.actionManager) {
  12354. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12355. }
  12356. };
  12357. this._onKeyUp = function (evt) {
  12358. if (_this.actionManager) {
  12359. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12360. }
  12361. };
  12362. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12363. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12364. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12365. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12366. // Wheel
  12367. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12368. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12369. BABYLON.Tools.RegisterTopRootEvents([
  12370. { name: "keydown", handler: this._onKeyDown },
  12371. { name: "keyup", handler: this._onKeyUp }
  12372. ]);
  12373. };
  12374. Scene.prototype.detachControl = function () {
  12375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12376. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12377. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12378. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12379. // Wheel
  12380. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12381. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12382. BABYLON.Tools.UnregisterTopRootEvents([
  12383. { name: "keydown", handler: this._onKeyDown },
  12384. { name: "keyup", handler: this._onKeyUp }
  12385. ]);
  12386. };
  12387. // Ready
  12388. Scene.prototype.isReady = function () {
  12389. if (this._pendingData.length > 0) {
  12390. return false;
  12391. }
  12392. var index;
  12393. for (index = 0; index < this._geometries.length; index++) {
  12394. var geometry = this._geometries[index];
  12395. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12396. return false;
  12397. }
  12398. }
  12399. for (index = 0; index < this.meshes.length; index++) {
  12400. var mesh = this.meshes[index];
  12401. if (!mesh.isReady()) {
  12402. return false;
  12403. }
  12404. var mat = mesh.material;
  12405. if (mat) {
  12406. if (!mat.isReady(mesh)) {
  12407. return false;
  12408. }
  12409. }
  12410. }
  12411. return true;
  12412. };
  12413. Scene.prototype.resetCachedMaterial = function () {
  12414. this._cachedMaterial = null;
  12415. };
  12416. Scene.prototype.registerBeforeRender = function (func) {
  12417. this._onBeforeRenderCallbacks.push(func);
  12418. };
  12419. Scene.prototype.unregisterBeforeRender = function (func) {
  12420. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12421. if (index > -1) {
  12422. this._onBeforeRenderCallbacks.splice(index, 1);
  12423. }
  12424. };
  12425. Scene.prototype.registerAfterRender = function (func) {
  12426. this._onAfterRenderCallbacks.push(func);
  12427. };
  12428. Scene.prototype.unregisterAfterRender = function (func) {
  12429. var index = this._onAfterRenderCallbacks.indexOf(func);
  12430. if (index > -1) {
  12431. this._onAfterRenderCallbacks.splice(index, 1);
  12432. }
  12433. };
  12434. Scene.prototype._addPendingData = function (data) {
  12435. this._pendingData.push(data);
  12436. };
  12437. Scene.prototype._removePendingData = function (data) {
  12438. var index = this._pendingData.indexOf(data);
  12439. if (index !== -1) {
  12440. this._pendingData.splice(index, 1);
  12441. }
  12442. };
  12443. Scene.prototype.getWaitingItemsCount = function () {
  12444. return this._pendingData.length;
  12445. };
  12446. /**
  12447. * Registers a function to be executed when the scene is ready.
  12448. * @param {Function} func - the function to be executed.
  12449. */
  12450. Scene.prototype.executeWhenReady = function (func) {
  12451. var _this = this;
  12452. this._onReadyCallbacks.push(func);
  12453. if (this._executeWhenReadyTimeoutId !== -1) {
  12454. return;
  12455. }
  12456. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12457. _this._checkIsReady();
  12458. }, 150);
  12459. };
  12460. Scene.prototype._checkIsReady = function () {
  12461. var _this = this;
  12462. if (this.isReady()) {
  12463. this._onReadyCallbacks.forEach(function (func) {
  12464. func();
  12465. });
  12466. this._onReadyCallbacks = [];
  12467. this._executeWhenReadyTimeoutId = -1;
  12468. return;
  12469. }
  12470. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12471. _this._checkIsReady();
  12472. }, 150);
  12473. };
  12474. // Animations
  12475. /**
  12476. * Will start the animation sequence of a given target
  12477. * @param target - the target
  12478. * @param {number} from - from which frame should animation start
  12479. * @param {number} to - till which frame should animation run.
  12480. * @param {boolean} [loop] - should the animation loop
  12481. * @param {number} [speedRatio] - the speed in which to run the animation
  12482. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12483. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12484. * @return {BABYLON.Animatable} the animatable object created for this animation
  12485. * @see BABYLON.Animatable
  12486. * @see http://doc.babylonjs.com/page.php?p=22081
  12487. */
  12488. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12489. if (speedRatio === void 0) { speedRatio = 1.0; }
  12490. this.stopAnimation(target);
  12491. if (!animatable) {
  12492. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12493. }
  12494. // Local animations
  12495. if (target.animations) {
  12496. animatable.appendAnimations(target, target.animations);
  12497. }
  12498. // Children animations
  12499. if (target.getAnimatables) {
  12500. var animatables = target.getAnimatables();
  12501. for (var index = 0; index < animatables.length; index++) {
  12502. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12503. }
  12504. }
  12505. return animatable;
  12506. };
  12507. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12508. if (speedRatio === undefined) {
  12509. speedRatio = 1.0;
  12510. }
  12511. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12512. return animatable;
  12513. };
  12514. Scene.prototype.getAnimatableByTarget = function (target) {
  12515. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12516. if (this._activeAnimatables[index].target === target) {
  12517. return this._activeAnimatables[index];
  12518. }
  12519. }
  12520. return null;
  12521. };
  12522. /**
  12523. * Will stop the animation of the given target
  12524. * @param target - the target
  12525. * @see beginAnimation
  12526. */
  12527. Scene.prototype.stopAnimation = function (target) {
  12528. var animatable = this.getAnimatableByTarget(target);
  12529. if (animatable) {
  12530. animatable.stop();
  12531. }
  12532. };
  12533. Scene.prototype._animate = function () {
  12534. if (!this.animationsEnabled) {
  12535. return;
  12536. }
  12537. if (!this._animationStartDate) {
  12538. this._animationStartDate = BABYLON.Tools.Now;
  12539. }
  12540. // Getting time
  12541. var now = BABYLON.Tools.Now;
  12542. var delay = now - this._animationStartDate;
  12543. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12544. this._activeAnimatables[index]._animate(delay);
  12545. }
  12546. };
  12547. // Matrix
  12548. Scene.prototype.getViewMatrix = function () {
  12549. return this._viewMatrix;
  12550. };
  12551. Scene.prototype.getProjectionMatrix = function () {
  12552. return this._projectionMatrix;
  12553. };
  12554. Scene.prototype.getTransformMatrix = function () {
  12555. return this._transformMatrix;
  12556. };
  12557. Scene.prototype.setTransformMatrix = function (view, projection) {
  12558. this._viewMatrix = view;
  12559. this._projectionMatrix = projection;
  12560. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12561. };
  12562. // Methods
  12563. Scene.prototype.addMesh = function (newMesh) {
  12564. newMesh.uniqueId = this._uniqueIdCounter++;
  12565. var position = this.meshes.push(newMesh);
  12566. //notify the collision coordinator
  12567. this.collisionCoordinator.onMeshAdded(newMesh);
  12568. if (this.onNewMeshAdded) {
  12569. this.onNewMeshAdded(newMesh, position, this);
  12570. }
  12571. };
  12572. Scene.prototype.removeMesh = function (toRemove) {
  12573. var index = this.meshes.indexOf(toRemove);
  12574. if (index !== -1) {
  12575. // Remove from the scene if mesh found
  12576. this.meshes.splice(index, 1);
  12577. }
  12578. //notify the collision coordinator
  12579. this.collisionCoordinator.onMeshRemoved(toRemove);
  12580. if (this.onMeshRemoved) {
  12581. this.onMeshRemoved(toRemove);
  12582. }
  12583. return index;
  12584. };
  12585. Scene.prototype.removeSkeleton = function (toRemove) {
  12586. var index = this.skeletons.indexOf(toRemove);
  12587. if (index !== -1) {
  12588. // Remove from the scene if mesh found
  12589. this.skeletons.splice(index, 1);
  12590. }
  12591. return index;
  12592. };
  12593. Scene.prototype.removeLight = function (toRemove) {
  12594. var index = this.lights.indexOf(toRemove);
  12595. if (index !== -1) {
  12596. // Remove from the scene if mesh found
  12597. this.lights.splice(index, 1);
  12598. }
  12599. if (this.onLightRemoved) {
  12600. this.onLightRemoved(toRemove);
  12601. }
  12602. return index;
  12603. };
  12604. Scene.prototype.removeCamera = function (toRemove) {
  12605. var index = this.cameras.indexOf(toRemove);
  12606. if (index !== -1) {
  12607. // Remove from the scene if mesh found
  12608. this.cameras.splice(index, 1);
  12609. }
  12610. // Remove from activeCameras
  12611. var index2 = this.activeCameras.indexOf(toRemove);
  12612. if (index2 !== -1) {
  12613. // Remove from the scene if mesh found
  12614. this.activeCameras.splice(index2, 1);
  12615. }
  12616. // Reset the activeCamera
  12617. if (this.activeCamera === toRemove) {
  12618. if (this.cameras.length > 0) {
  12619. this.activeCamera = this.cameras[0];
  12620. }
  12621. else {
  12622. this.activeCamera = null;
  12623. }
  12624. }
  12625. if (this.onCameraRemoved) {
  12626. this.onCameraRemoved(toRemove);
  12627. }
  12628. return index;
  12629. };
  12630. Scene.prototype.addLight = function (newLight) {
  12631. newLight.uniqueId = this._uniqueIdCounter++;
  12632. var position = this.lights.push(newLight);
  12633. if (this.onNewLightAdded) {
  12634. this.onNewLightAdded(newLight, position, this);
  12635. }
  12636. };
  12637. Scene.prototype.addCamera = function (newCamera) {
  12638. newCamera.uniqueId = this._uniqueIdCounter++;
  12639. var position = this.cameras.push(newCamera);
  12640. if (this.onNewCameraAdded) {
  12641. this.onNewCameraAdded(newCamera, position, this);
  12642. }
  12643. };
  12644. /**
  12645. * sets the active camera of the scene using its ID
  12646. * @param {string} id - the camera's ID
  12647. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12648. * @see activeCamera
  12649. */
  12650. Scene.prototype.setActiveCameraByID = function (id) {
  12651. var camera = this.getCameraByID(id);
  12652. if (camera) {
  12653. this.activeCamera = camera;
  12654. return camera;
  12655. }
  12656. return null;
  12657. };
  12658. /**
  12659. * sets the active camera of the scene using its name
  12660. * @param {string} name - the camera's name
  12661. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12662. * @see activeCamera
  12663. */
  12664. Scene.prototype.setActiveCameraByName = function (name) {
  12665. var camera = this.getCameraByName(name);
  12666. if (camera) {
  12667. this.activeCamera = camera;
  12668. return camera;
  12669. }
  12670. return null;
  12671. };
  12672. /**
  12673. * get a material using its id
  12674. * @param {string} the material's ID
  12675. * @return {BABYLON.Material|null} the material or null if none found.
  12676. */
  12677. Scene.prototype.getMaterialByID = function (id) {
  12678. for (var index = 0; index < this.materials.length; index++) {
  12679. if (this.materials[index].id === id) {
  12680. return this.materials[index];
  12681. }
  12682. }
  12683. return null;
  12684. };
  12685. /**
  12686. * get a material using its name
  12687. * @param {string} the material's name
  12688. * @return {BABYLON.Material|null} the material or null if none found.
  12689. */
  12690. Scene.prototype.getMaterialByName = function (name) {
  12691. for (var index = 0; index < this.materials.length; index++) {
  12692. if (this.materials[index].name === name) {
  12693. return this.materials[index];
  12694. }
  12695. }
  12696. return null;
  12697. };
  12698. Scene.prototype.getLensFlareSystemByName = function (name) {
  12699. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12700. if (this.lensFlareSystems[index].name === name) {
  12701. return this.lensFlareSystems[index];
  12702. }
  12703. }
  12704. return null;
  12705. };
  12706. Scene.prototype.getCameraByID = function (id) {
  12707. for (var index = 0; index < this.cameras.length; index++) {
  12708. if (this.cameras[index].id === id) {
  12709. return this.cameras[index];
  12710. }
  12711. }
  12712. return null;
  12713. };
  12714. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12715. for (var index = 0; index < this.cameras.length; index++) {
  12716. if (this.cameras[index].uniqueId === uniqueId) {
  12717. return this.cameras[index];
  12718. }
  12719. }
  12720. return null;
  12721. };
  12722. /**
  12723. * get a camera using its name
  12724. * @param {string} the camera's name
  12725. * @return {BABYLON.Camera|null} the camera or null if none found.
  12726. */
  12727. Scene.prototype.getCameraByName = function (name) {
  12728. for (var index = 0; index < this.cameras.length; index++) {
  12729. if (this.cameras[index].name === name) {
  12730. return this.cameras[index];
  12731. }
  12732. }
  12733. return null;
  12734. };
  12735. /**
  12736. * get a bone using its id
  12737. * @param {string} the bone's id
  12738. * @return {BABYLON.Bone|null} the bone or null if not found
  12739. */
  12740. Scene.prototype.getBoneByID = function (id) {
  12741. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12742. var skeleton = this.skeletons[skeletonIndex];
  12743. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12744. if (skeleton.bones[boneIndex].id === id) {
  12745. return skeleton.bones[boneIndex];
  12746. }
  12747. }
  12748. }
  12749. return null;
  12750. };
  12751. /**
  12752. * get a bone using its id
  12753. * @param {string} the bone's name
  12754. * @return {BABYLON.Bone|null} the bone or null if not found
  12755. */
  12756. Scene.prototype.getBoneByName = function (name) {
  12757. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12758. var skeleton = this.skeletons[skeletonIndex];
  12759. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12760. if (skeleton.bones[boneIndex].name === name) {
  12761. return skeleton.bones[boneIndex];
  12762. }
  12763. }
  12764. }
  12765. return null;
  12766. };
  12767. /**
  12768. * get a light node using its name
  12769. * @param {string} the light's name
  12770. * @return {BABYLON.Light|null} the light or null if none found.
  12771. */
  12772. Scene.prototype.getLightByName = function (name) {
  12773. for (var index = 0; index < this.lights.length; index++) {
  12774. if (this.lights[index].name === name) {
  12775. return this.lights[index];
  12776. }
  12777. }
  12778. return null;
  12779. };
  12780. /**
  12781. * get a light node using its ID
  12782. * @param {string} the light's id
  12783. * @return {BABYLON.Light|null} the light or null if none found.
  12784. */
  12785. Scene.prototype.getLightByID = function (id) {
  12786. for (var index = 0; index < this.lights.length; index++) {
  12787. if (this.lights[index].id === id) {
  12788. return this.lights[index];
  12789. }
  12790. }
  12791. return null;
  12792. };
  12793. /**
  12794. * get a light node using its scene-generated unique ID
  12795. * @param {number} the light's unique id
  12796. * @return {BABYLON.Light|null} the light or null if none found.
  12797. */
  12798. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12799. for (var index = 0; index < this.lights.length; index++) {
  12800. if (this.lights[index].uniqueId === uniqueId) {
  12801. return this.lights[index];
  12802. }
  12803. }
  12804. return null;
  12805. };
  12806. /**
  12807. * get a particle system by id
  12808. * @param id {number} the particle system id
  12809. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12810. */
  12811. Scene.prototype.getParticleSystemByID = function (id) {
  12812. for (var index = 0; index < this.particleSystems.length; index++) {
  12813. if (this.particleSystems[index].id === id) {
  12814. return this.particleSystems[index];
  12815. }
  12816. }
  12817. return null;
  12818. };
  12819. /**
  12820. * get a geometry using its ID
  12821. * @param {string} the geometry's id
  12822. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12823. */
  12824. Scene.prototype.getGeometryByID = function (id) {
  12825. for (var index = 0; index < this._geometries.length; index++) {
  12826. if (this._geometries[index].id === id) {
  12827. return this._geometries[index];
  12828. }
  12829. }
  12830. return null;
  12831. };
  12832. /**
  12833. * add a new geometry to this scene.
  12834. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12835. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12836. * @return {boolean} was the geometry added or not
  12837. */
  12838. Scene.prototype.pushGeometry = function (geometry, force) {
  12839. if (!force && this.getGeometryByID(geometry.id)) {
  12840. return false;
  12841. }
  12842. this._geometries.push(geometry);
  12843. //notify the collision coordinator
  12844. this.collisionCoordinator.onGeometryAdded(geometry);
  12845. if (this.onGeometryAdded) {
  12846. this.onGeometryAdded(geometry);
  12847. }
  12848. return true;
  12849. };
  12850. /**
  12851. * Removes an existing geometry
  12852. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12853. * @return {boolean} was the geometry removed or not
  12854. */
  12855. Scene.prototype.removeGeometry = function (geometry) {
  12856. var index = this._geometries.indexOf(geometry);
  12857. if (index > -1) {
  12858. this._geometries.splice(index, 1);
  12859. //notify the collision coordinator
  12860. this.collisionCoordinator.onGeometryDeleted(geometry);
  12861. if (this.onGeometryRemoved) {
  12862. this.onGeometryRemoved(geometry);
  12863. }
  12864. return true;
  12865. }
  12866. return false;
  12867. };
  12868. Scene.prototype.getGeometries = function () {
  12869. return this._geometries;
  12870. };
  12871. /**
  12872. * Get the first added mesh found of a given ID
  12873. * @param {string} id - the id to search for
  12874. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12875. */
  12876. Scene.prototype.getMeshByID = function (id) {
  12877. for (var index = 0; index < this.meshes.length; index++) {
  12878. if (this.meshes[index].id === id) {
  12879. return this.meshes[index];
  12880. }
  12881. }
  12882. return null;
  12883. };
  12884. /**
  12885. * Get a mesh with its auto-generated unique id
  12886. * @param {number} uniqueId - the unique id to search for
  12887. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12888. */
  12889. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12890. for (var index = 0; index < this.meshes.length; index++) {
  12891. if (this.meshes[index].uniqueId === uniqueId) {
  12892. return this.meshes[index];
  12893. }
  12894. }
  12895. return null;
  12896. };
  12897. /**
  12898. * Get a the last added mesh found of a given ID
  12899. * @param {string} id - the id to search for
  12900. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12901. */
  12902. Scene.prototype.getLastMeshByID = function (id) {
  12903. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12904. if (this.meshes[index].id === id) {
  12905. return this.meshes[index];
  12906. }
  12907. }
  12908. return null;
  12909. };
  12910. /**
  12911. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12912. * @param {string} id - the id to search for
  12913. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12914. */
  12915. Scene.prototype.getLastEntryByID = function (id) {
  12916. var index;
  12917. for (index = this.meshes.length - 1; index >= 0; index--) {
  12918. if (this.meshes[index].id === id) {
  12919. return this.meshes[index];
  12920. }
  12921. }
  12922. for (index = this.cameras.length - 1; index >= 0; index--) {
  12923. if (this.cameras[index].id === id) {
  12924. return this.cameras[index];
  12925. }
  12926. }
  12927. for (index = this.lights.length - 1; index >= 0; index--) {
  12928. if (this.lights[index].id === id) {
  12929. return this.lights[index];
  12930. }
  12931. }
  12932. return null;
  12933. };
  12934. Scene.prototype.getNodeByID = function (id) {
  12935. var mesh = this.getMeshByID(id);
  12936. if (mesh) {
  12937. return mesh;
  12938. }
  12939. var light = this.getLightByID(id);
  12940. if (light) {
  12941. return light;
  12942. }
  12943. var camera = this.getCameraByID(id);
  12944. if (camera) {
  12945. return camera;
  12946. }
  12947. var bone = this.getBoneByID(id);
  12948. return bone;
  12949. };
  12950. Scene.prototype.getNodeByName = function (name) {
  12951. var mesh = this.getMeshByName(name);
  12952. if (mesh) {
  12953. return mesh;
  12954. }
  12955. var light = this.getLightByName(name);
  12956. if (light) {
  12957. return light;
  12958. }
  12959. var camera = this.getCameraByName(name);
  12960. if (camera) {
  12961. return camera;
  12962. }
  12963. var bone = this.getBoneByName(name);
  12964. return bone;
  12965. };
  12966. Scene.prototype.getMeshByName = function (name) {
  12967. for (var index = 0; index < this.meshes.length; index++) {
  12968. if (this.meshes[index].name === name) {
  12969. return this.meshes[index];
  12970. }
  12971. }
  12972. return null;
  12973. };
  12974. Scene.prototype.getSoundByName = function (name) {
  12975. var index;
  12976. if (BABYLON.AudioEngine) {
  12977. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12978. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12979. return this.mainSoundTrack.soundCollection[index];
  12980. }
  12981. }
  12982. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12983. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12984. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12985. return this.soundTracks[sdIndex].soundCollection[index];
  12986. }
  12987. }
  12988. }
  12989. }
  12990. return null;
  12991. };
  12992. Scene.prototype.getLastSkeletonByID = function (id) {
  12993. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12994. if (this.skeletons[index].id === id) {
  12995. return this.skeletons[index];
  12996. }
  12997. }
  12998. return null;
  12999. };
  13000. Scene.prototype.getSkeletonById = function (id) {
  13001. for (var index = 0; index < this.skeletons.length; index++) {
  13002. if (this.skeletons[index].id === id) {
  13003. return this.skeletons[index];
  13004. }
  13005. }
  13006. return null;
  13007. };
  13008. Scene.prototype.getSkeletonByName = function (name) {
  13009. for (var index = 0; index < this.skeletons.length; index++) {
  13010. if (this.skeletons[index].name === name) {
  13011. return this.skeletons[index];
  13012. }
  13013. }
  13014. return null;
  13015. };
  13016. Scene.prototype.isActiveMesh = function (mesh) {
  13017. return (this._activeMeshes.indexOf(mesh) !== -1);
  13018. };
  13019. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13020. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13021. var material = subMesh.getMaterial();
  13022. if (mesh.showSubMeshesBoundingBox) {
  13023. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13024. }
  13025. if (material) {
  13026. // Render targets
  13027. if (material.getRenderTargetTextures) {
  13028. if (this._processedMaterials.indexOf(material) === -1) {
  13029. this._processedMaterials.push(material);
  13030. this._renderTargets.concat(material.getRenderTargetTextures());
  13031. }
  13032. }
  13033. // Dispatch
  13034. this._activeIndices += subMesh.indexCount;
  13035. this._renderingManager.dispatch(subMesh);
  13036. }
  13037. }
  13038. };
  13039. Scene.prototype._evaluateActiveMeshes = function () {
  13040. this.activeCamera._activeMeshes.reset();
  13041. this._activeMeshes.reset();
  13042. this._renderingManager.reset();
  13043. this._processedMaterials.reset();
  13044. this._activeParticleSystems.reset();
  13045. this._activeSkeletons.reset();
  13046. this._softwareSkinnedMeshes.reset();
  13047. this._boundingBoxRenderer.reset();
  13048. this._edgesRenderers.reset();
  13049. if (!this._frustumPlanes) {
  13050. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13051. }
  13052. else {
  13053. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13054. }
  13055. // Meshes
  13056. var meshes;
  13057. var len;
  13058. if (this._selectionOctree) {
  13059. var selection = this._selectionOctree.select(this._frustumPlanes);
  13060. meshes = selection.data;
  13061. len = selection.length;
  13062. }
  13063. else {
  13064. len = this.meshes.length;
  13065. meshes = this.meshes;
  13066. }
  13067. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13068. var mesh = meshes[meshIndex];
  13069. if (mesh.isBlocked) {
  13070. continue;
  13071. }
  13072. this._totalVertices += mesh.getTotalVertices();
  13073. if (!mesh.isReady() || !mesh.isEnabled()) {
  13074. continue;
  13075. }
  13076. mesh.computeWorldMatrix();
  13077. // Intersections
  13078. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13079. this._meshesForIntersections.pushNoDuplicate(mesh);
  13080. }
  13081. // Switch to current LOD
  13082. var meshLOD = mesh.getLOD(this.activeCamera);
  13083. if (!meshLOD) {
  13084. continue;
  13085. }
  13086. mesh._preActivate();
  13087. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13088. this._activeMeshes.push(mesh);
  13089. this.activeCamera._activeMeshes.push(mesh);
  13090. mesh._activate(this._renderId);
  13091. this._activeMesh(meshLOD);
  13092. }
  13093. }
  13094. // Particle systems
  13095. var beforeParticlesDate = BABYLON.Tools.Now;
  13096. if (this.particlesEnabled) {
  13097. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13098. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13099. var particleSystem = this.particleSystems[particleIndex];
  13100. if (!particleSystem.isStarted()) {
  13101. continue;
  13102. }
  13103. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13104. this._activeParticleSystems.push(particleSystem);
  13105. particleSystem.animate();
  13106. }
  13107. }
  13108. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13109. }
  13110. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13111. };
  13112. Scene.prototype._activeMesh = function (mesh) {
  13113. if (mesh.skeleton && this.skeletonsEnabled) {
  13114. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13115. if (!mesh.computeBonesUsingShaders) {
  13116. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13117. }
  13118. }
  13119. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13120. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13121. }
  13122. if (mesh._edgesRenderer) {
  13123. this._edgesRenderers.push(mesh._edgesRenderer);
  13124. }
  13125. if (mesh && mesh.subMeshes) {
  13126. // Submeshes Octrees
  13127. var len;
  13128. var subMeshes;
  13129. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13130. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13131. len = intersections.length;
  13132. subMeshes = intersections.data;
  13133. }
  13134. else {
  13135. subMeshes = mesh.subMeshes;
  13136. len = subMeshes.length;
  13137. }
  13138. for (var subIndex = 0; subIndex < len; subIndex++) {
  13139. var subMesh = subMeshes[subIndex];
  13140. this._evaluateSubMesh(subMesh, mesh);
  13141. }
  13142. }
  13143. };
  13144. Scene.prototype.updateTransformMatrix = function (force) {
  13145. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13146. };
  13147. Scene.prototype._renderForCamera = function (camera) {
  13148. var engine = this._engine;
  13149. this.activeCamera = camera;
  13150. if (!this.activeCamera)
  13151. throw new Error("Active camera not set");
  13152. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13153. // Viewport
  13154. engine.setViewport(this.activeCamera.viewport);
  13155. // Camera
  13156. this.resetCachedMaterial();
  13157. this._renderId++;
  13158. this.updateTransformMatrix();
  13159. if (this.beforeCameraRender) {
  13160. this.beforeCameraRender(this.activeCamera);
  13161. }
  13162. // Meshes
  13163. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13164. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13165. this._evaluateActiveMeshes();
  13166. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13167. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13168. // Skeletons
  13169. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13170. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13171. skeleton.prepare();
  13172. }
  13173. // Software skinning
  13174. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13175. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13176. mesh.applySkeleton(mesh.skeleton);
  13177. }
  13178. // Render targets
  13179. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13180. if (this.renderTargetsEnabled) {
  13181. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13182. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13183. var renderTarget = this._renderTargets.data[renderIndex];
  13184. if (renderTarget._shouldRender()) {
  13185. this._renderId++;
  13186. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13187. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13188. }
  13189. }
  13190. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13191. this._renderId++;
  13192. }
  13193. if (this._renderTargets.length > 0) {
  13194. engine.restoreDefaultFramebuffer();
  13195. }
  13196. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13197. // Prepare Frame
  13198. this.postProcessManager._prepareFrame();
  13199. var beforeRenderDate = BABYLON.Tools.Now;
  13200. // Backgrounds
  13201. var layerIndex;
  13202. var layer;
  13203. if (this.layers.length) {
  13204. engine.setDepthBuffer(false);
  13205. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13206. layer = this.layers[layerIndex];
  13207. if (layer.isBackground) {
  13208. layer.render();
  13209. }
  13210. }
  13211. engine.setDepthBuffer(true);
  13212. }
  13213. // Render
  13214. BABYLON.Tools.StartPerformanceCounter("Main render");
  13215. this._renderingManager.render(null, null, true, true);
  13216. BABYLON.Tools.EndPerformanceCounter("Main render");
  13217. // Bounding boxes
  13218. this._boundingBoxRenderer.render();
  13219. // Edges
  13220. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13221. this._edgesRenderers.data[edgesRendererIndex].render();
  13222. }
  13223. // Lens flares
  13224. if (this.lensFlaresEnabled) {
  13225. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13226. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13227. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13228. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13229. lensFlareSystem.render();
  13230. }
  13231. }
  13232. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13233. }
  13234. // Foregrounds
  13235. if (this.layers.length) {
  13236. engine.setDepthBuffer(false);
  13237. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13238. layer = this.layers[layerIndex];
  13239. if (!layer.isBackground) {
  13240. layer.render();
  13241. }
  13242. }
  13243. engine.setDepthBuffer(true);
  13244. }
  13245. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13246. // Finalize frame
  13247. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13248. // Update camera
  13249. this.activeCamera._updateFromScene();
  13250. // Reset some special arrays
  13251. this._renderTargets.reset();
  13252. if (this.afterCameraRender) {
  13253. this.afterCameraRender(this.activeCamera);
  13254. }
  13255. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13256. };
  13257. Scene.prototype._processSubCameras = function (camera) {
  13258. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13259. this._renderForCamera(camera);
  13260. return;
  13261. }
  13262. // rig cameras
  13263. for (var index = 0; index < camera._rigCameras.length; index++) {
  13264. this._renderForCamera(camera._rigCameras[index]);
  13265. }
  13266. this.activeCamera = camera;
  13267. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13268. // Update camera
  13269. this.activeCamera._updateFromScene();
  13270. };
  13271. Scene.prototype._checkIntersections = function () {
  13272. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13273. var sourceMesh = this._meshesForIntersections.data[index];
  13274. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13275. var action = sourceMesh.actionManager.actions[actionIndex];
  13276. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13277. var parameters = action.getTriggerParameter();
  13278. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13279. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13280. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13281. if (areIntersecting && currentIntersectionInProgress === -1) {
  13282. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13283. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13284. sourceMesh._intersectionsInProgress.push(otherMesh);
  13285. }
  13286. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13287. sourceMesh._intersectionsInProgress.push(otherMesh);
  13288. }
  13289. }
  13290. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13291. //They intersected, and now they don't.
  13292. //is this trigger an exit trigger? execute an event.
  13293. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13294. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13295. }
  13296. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13297. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13298. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13299. }
  13300. }
  13301. }
  13302. }
  13303. }
  13304. };
  13305. Scene.prototype.render = function () {
  13306. var startDate = BABYLON.Tools.Now;
  13307. this._particlesDuration = 0;
  13308. this._spritesDuration = 0;
  13309. this._activeParticles = 0;
  13310. this._renderDuration = 0;
  13311. this._renderTargetsDuration = 0;
  13312. this._evaluateActiveMeshesDuration = 0;
  13313. this._totalVertices = 0;
  13314. this._activeIndices = 0;
  13315. this._activeBones = 0;
  13316. this.getEngine().resetDrawCalls();
  13317. this._meshesForIntersections.reset();
  13318. this.resetCachedMaterial();
  13319. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13320. // Actions
  13321. if (this.actionManager) {
  13322. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13323. }
  13324. //Simplification Queue
  13325. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13326. this.simplificationQueue.executeNext();
  13327. }
  13328. // Animations
  13329. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13330. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13331. this._animate();
  13332. // Physics
  13333. if (this._physicsEngine) {
  13334. BABYLON.Tools.StartPerformanceCounter("Physics");
  13335. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13336. BABYLON.Tools.EndPerformanceCounter("Physics");
  13337. }
  13338. // Before render
  13339. if (this.beforeRender) {
  13340. this.beforeRender();
  13341. }
  13342. var callbackIndex;
  13343. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13344. this._onBeforeRenderCallbacks[callbackIndex]();
  13345. }
  13346. // Customs render targets
  13347. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13348. var engine = this.getEngine();
  13349. var currentActiveCamera = this.activeCamera;
  13350. if (this.renderTargetsEnabled) {
  13351. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13352. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13353. var renderTarget = this.customRenderTargets[customIndex];
  13354. if (renderTarget._shouldRender()) {
  13355. this._renderId++;
  13356. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13357. if (!this.activeCamera)
  13358. throw new Error("Active camera not set");
  13359. // Viewport
  13360. engine.setViewport(this.activeCamera.viewport);
  13361. // Camera
  13362. this.updateTransformMatrix();
  13363. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13364. }
  13365. }
  13366. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13367. this._renderId++;
  13368. }
  13369. if (this.customRenderTargets.length > 0) {
  13370. engine.restoreDefaultFramebuffer();
  13371. }
  13372. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13373. this.activeCamera = currentActiveCamera;
  13374. // Procedural textures
  13375. if (this.proceduralTexturesEnabled) {
  13376. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13377. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13378. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13379. if (proceduralTexture._shouldRender()) {
  13380. proceduralTexture.render();
  13381. }
  13382. }
  13383. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13384. }
  13385. // Clear
  13386. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13387. // Shadows
  13388. if (this.shadowsEnabled) {
  13389. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13390. var light = this.lights[lightIndex];
  13391. var shadowGenerator = light.getShadowGenerator();
  13392. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13393. this._renderTargets.push(shadowGenerator.getShadowMap());
  13394. }
  13395. }
  13396. }
  13397. // Depth renderer
  13398. if (this._depthRenderer) {
  13399. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13400. }
  13401. // RenderPipeline
  13402. this.postProcessRenderPipelineManager.update();
  13403. // Multi-cameras?
  13404. if (this.activeCameras.length > 0) {
  13405. var currentRenderId = this._renderId;
  13406. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13407. this._renderId = currentRenderId;
  13408. this._processSubCameras(this.activeCameras[cameraIndex]);
  13409. }
  13410. }
  13411. else {
  13412. if (!this.activeCamera) {
  13413. throw new Error("No camera defined");
  13414. }
  13415. this._processSubCameras(this.activeCamera);
  13416. }
  13417. // Intersection checks
  13418. this._checkIntersections();
  13419. // Update the audio listener attached to the camera
  13420. if (BABYLON.AudioEngine) {
  13421. this._updateAudioParameters();
  13422. }
  13423. // After render
  13424. if (this.afterRender) {
  13425. this.afterRender();
  13426. }
  13427. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13428. this._onAfterRenderCallbacks[callbackIndex]();
  13429. }
  13430. // Cleaning
  13431. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13432. this._toBeDisposed.data[index].dispose();
  13433. this._toBeDisposed[index] = null;
  13434. }
  13435. this._toBeDisposed.reset();
  13436. if (this.dumpNextRenderTargets) {
  13437. this.dumpNextRenderTargets = false;
  13438. }
  13439. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13440. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13441. };
  13442. Scene.prototype._updateAudioParameters = function () {
  13443. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13444. return;
  13445. }
  13446. var listeningCamera;
  13447. var audioEngine = BABYLON.Engine.audioEngine;
  13448. if (this.activeCameras.length > 0) {
  13449. listeningCamera = this.activeCameras[0];
  13450. }
  13451. else {
  13452. listeningCamera = this.activeCamera;
  13453. }
  13454. if (listeningCamera && audioEngine.canUseWebAudio) {
  13455. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13456. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13457. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13458. cameraDirection.normalize();
  13459. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13460. var i;
  13461. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13462. var sound = this.mainSoundTrack.soundCollection[i];
  13463. if (sound.useCustomAttenuation) {
  13464. sound.updateDistanceFromListener();
  13465. }
  13466. }
  13467. for (i = 0; i < this.soundTracks.length; i++) {
  13468. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13469. sound = this.soundTracks[i].soundCollection[j];
  13470. if (sound.useCustomAttenuation) {
  13471. sound.updateDistanceFromListener();
  13472. }
  13473. }
  13474. }
  13475. }
  13476. };
  13477. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13478. // Audio
  13479. get: function () {
  13480. return this._audioEnabled;
  13481. },
  13482. set: function (value) {
  13483. this._audioEnabled = value;
  13484. if (BABYLON.AudioEngine) {
  13485. if (this._audioEnabled) {
  13486. this._enableAudio();
  13487. }
  13488. else {
  13489. this._disableAudio();
  13490. }
  13491. }
  13492. },
  13493. enumerable: true,
  13494. configurable: true
  13495. });
  13496. Scene.prototype._disableAudio = function () {
  13497. var i;
  13498. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13499. this.mainSoundTrack.soundCollection[i].pause();
  13500. }
  13501. for (i = 0; i < this.soundTracks.length; i++) {
  13502. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13503. this.soundTracks[i].soundCollection[j].pause();
  13504. }
  13505. }
  13506. };
  13507. Scene.prototype._enableAudio = function () {
  13508. var i;
  13509. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13510. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13511. this.mainSoundTrack.soundCollection[i].play();
  13512. }
  13513. }
  13514. for (i = 0; i < this.soundTracks.length; i++) {
  13515. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13516. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13517. this.soundTracks[i].soundCollection[j].play();
  13518. }
  13519. }
  13520. }
  13521. };
  13522. Object.defineProperty(Scene.prototype, "headphone", {
  13523. get: function () {
  13524. return this._headphone;
  13525. },
  13526. set: function (value) {
  13527. this._headphone = value;
  13528. if (BABYLON.AudioEngine) {
  13529. if (this._headphone) {
  13530. this._switchAudioModeForHeadphones();
  13531. }
  13532. else {
  13533. this._switchAudioModeForNormalSpeakers();
  13534. }
  13535. }
  13536. },
  13537. enumerable: true,
  13538. configurable: true
  13539. });
  13540. Scene.prototype._switchAudioModeForHeadphones = function () {
  13541. this.mainSoundTrack.switchPanningModelToHRTF();
  13542. for (var i = 0; i < this.soundTracks.length; i++) {
  13543. this.soundTracks[i].switchPanningModelToHRTF();
  13544. }
  13545. };
  13546. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13547. this.mainSoundTrack.switchPanningModelToEqualPower();
  13548. for (var i = 0; i < this.soundTracks.length; i++) {
  13549. this.soundTracks[i].switchPanningModelToEqualPower();
  13550. }
  13551. };
  13552. Scene.prototype.enableDepthRenderer = function () {
  13553. if (this._depthRenderer) {
  13554. return this._depthRenderer;
  13555. }
  13556. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13557. return this._depthRenderer;
  13558. };
  13559. Scene.prototype.disableDepthRenderer = function () {
  13560. if (!this._depthRenderer) {
  13561. return;
  13562. }
  13563. this._depthRenderer.dispose();
  13564. this._depthRenderer = null;
  13565. };
  13566. Scene.prototype.dispose = function () {
  13567. this.beforeRender = null;
  13568. this.afterRender = null;
  13569. this.skeletons = [];
  13570. this._boundingBoxRenderer.dispose();
  13571. if (this._depthRenderer) {
  13572. this._depthRenderer.dispose();
  13573. }
  13574. // Debug layer
  13575. this.debugLayer.hide();
  13576. // Events
  13577. if (this.onDispose) {
  13578. this.onDispose();
  13579. }
  13580. this._onBeforeRenderCallbacks = [];
  13581. this._onAfterRenderCallbacks = [];
  13582. this.detachControl();
  13583. // Release sounds & sounds tracks
  13584. if (BABYLON.AudioEngine) {
  13585. this.disposeSounds();
  13586. }
  13587. // Detach cameras
  13588. var canvas = this._engine.getRenderingCanvas();
  13589. var index;
  13590. for (index = 0; index < this.cameras.length; index++) {
  13591. this.cameras[index].detachControl(canvas);
  13592. }
  13593. // Release lights
  13594. while (this.lights.length) {
  13595. this.lights[0].dispose();
  13596. }
  13597. // Release meshes
  13598. while (this.meshes.length) {
  13599. this.meshes[0].dispose(true);
  13600. }
  13601. // Release cameras
  13602. while (this.cameras.length) {
  13603. this.cameras[0].dispose();
  13604. }
  13605. // Release materials
  13606. while (this.materials.length) {
  13607. this.materials[0].dispose();
  13608. }
  13609. // Release particles
  13610. while (this.particleSystems.length) {
  13611. this.particleSystems[0].dispose();
  13612. }
  13613. // Release sprites
  13614. while (this.spriteManagers.length) {
  13615. this.spriteManagers[0].dispose();
  13616. }
  13617. // Release layers
  13618. while (this.layers.length) {
  13619. this.layers[0].dispose();
  13620. }
  13621. // Release textures
  13622. while (this.textures.length) {
  13623. this.textures[0].dispose();
  13624. }
  13625. // Post-processes
  13626. this.postProcessManager.dispose();
  13627. // Physics
  13628. if (this._physicsEngine) {
  13629. this.disablePhysicsEngine();
  13630. }
  13631. // Remove from engine
  13632. index = this._engine.scenes.indexOf(this);
  13633. if (index > -1) {
  13634. this._engine.scenes.splice(index, 1);
  13635. }
  13636. this._engine.wipeCaches();
  13637. };
  13638. // Release sounds & sounds tracks
  13639. Scene.prototype.disposeSounds = function () {
  13640. this.mainSoundTrack.dispose();
  13641. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13642. this.soundTracks[scIndex].dispose();
  13643. }
  13644. };
  13645. // Octrees
  13646. Scene.prototype.getWorldExtends = function () {
  13647. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13648. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13649. for (var index = 0; index < this.meshes.length; index++) {
  13650. var mesh = this.meshes[index];
  13651. mesh.computeWorldMatrix(true);
  13652. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13653. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13654. BABYLON.Tools.CheckExtends(minBox, min, max);
  13655. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13656. }
  13657. return {
  13658. min: min,
  13659. max: max
  13660. };
  13661. };
  13662. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13663. if (maxCapacity === void 0) { maxCapacity = 64; }
  13664. if (maxDepth === void 0) { maxDepth = 2; }
  13665. if (!this._selectionOctree) {
  13666. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13667. }
  13668. var worldExtends = this.getWorldExtends();
  13669. // Update octree
  13670. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13671. return this._selectionOctree;
  13672. };
  13673. // Picking
  13674. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13675. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13676. var engine = this._engine;
  13677. if (!camera) {
  13678. if (!this.activeCamera)
  13679. throw new Error("Active camera not set");
  13680. camera = this.activeCamera;
  13681. }
  13682. var cameraViewport = camera.viewport;
  13683. var viewport = cameraViewport.toGlobal(engine);
  13684. // Moving coordinates to local viewport world
  13685. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13686. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13687. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13688. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13689. };
  13690. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13691. var engine = this._engine;
  13692. if (!camera) {
  13693. if (!this.activeCamera)
  13694. throw new Error("Active camera not set");
  13695. camera = this.activeCamera;
  13696. }
  13697. var cameraViewport = camera.viewport;
  13698. var viewport = cameraViewport.toGlobal(engine);
  13699. var identity = BABYLON.Matrix.Identity();
  13700. // Moving coordinates to local viewport world
  13701. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13702. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13703. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13704. };
  13705. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13706. var pickingInfo = null;
  13707. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13708. var mesh = this.meshes[meshIndex];
  13709. if (predicate) {
  13710. if (!predicate(mesh)) {
  13711. continue;
  13712. }
  13713. }
  13714. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13715. continue;
  13716. }
  13717. var world = mesh.getWorldMatrix();
  13718. var ray = rayFunction(world);
  13719. var result = mesh.intersects(ray, fastCheck);
  13720. if (!result || !result.hit)
  13721. continue;
  13722. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13723. continue;
  13724. pickingInfo = result;
  13725. if (fastCheck) {
  13726. break;
  13727. }
  13728. }
  13729. return pickingInfo || new BABYLON.PickingInfo();
  13730. };
  13731. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13732. var pickingInfo = null;
  13733. camera = camera || this.activeCamera;
  13734. if (this.spriteManagers.length > 0) {
  13735. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13736. var spriteManager = this.spriteManagers[spriteIndex];
  13737. if (!spriteManager.isPickable) {
  13738. continue;
  13739. }
  13740. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13741. if (!result || !result.hit)
  13742. continue;
  13743. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13744. continue;
  13745. pickingInfo = result;
  13746. if (fastCheck) {
  13747. break;
  13748. }
  13749. }
  13750. }
  13751. return pickingInfo || new BABYLON.PickingInfo();
  13752. };
  13753. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13754. var _this = this;
  13755. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13756. /// <param name="x">X position on screen</param>
  13757. /// <param name="y">Y position on screen</param>
  13758. /// <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>
  13759. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13760. /// <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>
  13761. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13762. };
  13763. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13764. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13765. /// <param name="x">X position on screen</param>
  13766. /// <param name="y">Y position on screen</param>
  13767. /// <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>
  13768. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13769. /// <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>
  13770. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13771. };
  13772. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13773. var _this = this;
  13774. return this._internalPick(function (world) {
  13775. if (!_this._pickWithRayInverseMatrix) {
  13776. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13777. }
  13778. world.invertToRef(_this._pickWithRayInverseMatrix);
  13779. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13780. }, predicate, fastCheck);
  13781. };
  13782. Scene.prototype.setPointerOverMesh = function (mesh) {
  13783. if (this._pointerOverMesh === mesh) {
  13784. return;
  13785. }
  13786. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13787. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13788. }
  13789. this._pointerOverMesh = mesh;
  13790. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13791. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13792. }
  13793. };
  13794. Scene.prototype.getPointerOverMesh = function () {
  13795. return this._pointerOverMesh;
  13796. };
  13797. // Physics
  13798. Scene.prototype.getPhysicsEngine = function () {
  13799. return this._physicsEngine;
  13800. };
  13801. /**
  13802. * Enables physics to the current scene
  13803. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13804. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13805. * @return {boolean} was the physics engine initialized
  13806. */
  13807. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13808. if (this._physicsEngine) {
  13809. return true;
  13810. }
  13811. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13812. if (!this._physicsEngine.isSupported()) {
  13813. this._physicsEngine = null;
  13814. return false;
  13815. }
  13816. this._physicsEngine._initialize(gravity);
  13817. return true;
  13818. };
  13819. Scene.prototype.disablePhysicsEngine = function () {
  13820. if (!this._physicsEngine) {
  13821. return;
  13822. }
  13823. this._physicsEngine.dispose();
  13824. this._physicsEngine = undefined;
  13825. };
  13826. Scene.prototype.isPhysicsEnabled = function () {
  13827. return this._physicsEngine !== undefined;
  13828. };
  13829. /**
  13830. * Sets the gravity of the physics engine (and NOT of the scene)
  13831. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13832. */
  13833. Scene.prototype.setGravity = function (gravity) {
  13834. if (!this._physicsEngine) {
  13835. return;
  13836. }
  13837. this._physicsEngine._setGravity(gravity);
  13838. };
  13839. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13840. if (parts.parts) {
  13841. options = parts;
  13842. parts = parts.parts;
  13843. }
  13844. if (!this._physicsEngine) {
  13845. return null;
  13846. }
  13847. for (var index = 0; index < parts.length; index++) {
  13848. var mesh = parts[index].mesh;
  13849. mesh._physicImpostor = parts[index].impostor;
  13850. mesh._physicsMass = options.mass / parts.length;
  13851. mesh._physicsFriction = options.friction;
  13852. mesh._physicRestitution = options.restitution;
  13853. }
  13854. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13855. };
  13856. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13857. for (var index = 0; index < compound.parts.length; index++) {
  13858. var mesh = compound.parts[index].mesh;
  13859. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13860. this._physicsEngine._unregisterMesh(mesh);
  13861. }
  13862. };
  13863. // Misc.
  13864. Scene.prototype.createDefaultCameraOrLight = function () {
  13865. // Light
  13866. if (this.lights.length === 0) {
  13867. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13868. }
  13869. // Camera
  13870. if (!this.activeCamera) {
  13871. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13872. // Compute position
  13873. var worldExtends = this.getWorldExtends();
  13874. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13875. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13876. camera.setTarget(worldCenter);
  13877. this.activeCamera = camera;
  13878. }
  13879. };
  13880. // Tags
  13881. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13882. if (tagsQuery === undefined) {
  13883. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13884. return list;
  13885. }
  13886. var listByTags = [];
  13887. forEach = forEach || (function (item) { return; });
  13888. for (var i in list) {
  13889. var item = list[i];
  13890. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13891. listByTags.push(item);
  13892. forEach(item);
  13893. }
  13894. }
  13895. return listByTags;
  13896. };
  13897. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13898. return this._getByTags(this.meshes, tagsQuery, forEach);
  13899. };
  13900. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13901. return this._getByTags(this.cameras, tagsQuery, forEach);
  13902. };
  13903. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13904. return this._getByTags(this.lights, tagsQuery, forEach);
  13905. };
  13906. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13907. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13908. };
  13909. // Statics
  13910. Scene._FOGMODE_NONE = 0;
  13911. Scene._FOGMODE_EXP = 1;
  13912. Scene._FOGMODE_EXP2 = 2;
  13913. Scene._FOGMODE_LINEAR = 3;
  13914. Scene.MinDeltaTime = 1.0;
  13915. Scene.MaxDeltaTime = 1000.0;
  13916. return Scene;
  13917. })();
  13918. BABYLON.Scene = Scene;
  13919. })(BABYLON || (BABYLON = {}));
  13920. var BABYLON;
  13921. (function (BABYLON) {
  13922. var VertexBuffer = (function () {
  13923. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13924. if (engine instanceof BABYLON.Mesh) {
  13925. this._engine = engine.getScene().getEngine();
  13926. }
  13927. else {
  13928. this._engine = engine;
  13929. }
  13930. this._updatable = updatable;
  13931. this._data = data;
  13932. if (!postponeInternalCreation) {
  13933. this.create();
  13934. }
  13935. this._kind = kind;
  13936. if (stride) {
  13937. this._strideSize = stride;
  13938. return;
  13939. }
  13940. // Deduce stride from kind
  13941. switch (kind) {
  13942. case VertexBuffer.PositionKind:
  13943. this._strideSize = 3;
  13944. break;
  13945. case VertexBuffer.NormalKind:
  13946. this._strideSize = 3;
  13947. break;
  13948. case VertexBuffer.UVKind:
  13949. case VertexBuffer.UV2Kind:
  13950. case VertexBuffer.UV3Kind:
  13951. case VertexBuffer.UV4Kind:
  13952. case VertexBuffer.UV5Kind:
  13953. case VertexBuffer.UV6Kind:
  13954. this._strideSize = 2;
  13955. break;
  13956. case VertexBuffer.ColorKind:
  13957. this._strideSize = 4;
  13958. break;
  13959. case VertexBuffer.MatricesIndicesKind:
  13960. case VertexBuffer.MatricesIndicesExtraKind:
  13961. this._strideSize = 4;
  13962. break;
  13963. case VertexBuffer.MatricesWeightsKind:
  13964. case VertexBuffer.MatricesWeightsExtraKind:
  13965. this._strideSize = 4;
  13966. break;
  13967. }
  13968. }
  13969. // Properties
  13970. VertexBuffer.prototype.isUpdatable = function () {
  13971. return this._updatable;
  13972. };
  13973. VertexBuffer.prototype.getData = function () {
  13974. return this._data;
  13975. };
  13976. VertexBuffer.prototype.getBuffer = function () {
  13977. return this._buffer;
  13978. };
  13979. VertexBuffer.prototype.getStrideSize = function () {
  13980. return this._strideSize;
  13981. };
  13982. // Methods
  13983. VertexBuffer.prototype.create = function (data) {
  13984. if (!data && this._buffer) {
  13985. return; // nothing to do
  13986. }
  13987. data = data || this._data;
  13988. if (!this._buffer) {
  13989. if (this._updatable) {
  13990. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13991. }
  13992. else {
  13993. this._buffer = this._engine.createVertexBuffer(data);
  13994. }
  13995. }
  13996. if (this._updatable) {
  13997. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13998. this._data = data;
  13999. }
  14000. };
  14001. VertexBuffer.prototype.update = function (data) {
  14002. this.create(data);
  14003. };
  14004. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14005. if (!this._buffer) {
  14006. return;
  14007. }
  14008. if (this._updatable) {
  14009. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14010. this._data = null;
  14011. }
  14012. };
  14013. VertexBuffer.prototype.dispose = function () {
  14014. if (!this._buffer) {
  14015. return;
  14016. }
  14017. if (this._engine._releaseBuffer(this._buffer)) {
  14018. this._buffer = null;
  14019. }
  14020. };
  14021. Object.defineProperty(VertexBuffer, "PositionKind", {
  14022. get: function () {
  14023. return VertexBuffer._PositionKind;
  14024. },
  14025. enumerable: true,
  14026. configurable: true
  14027. });
  14028. Object.defineProperty(VertexBuffer, "NormalKind", {
  14029. get: function () {
  14030. return VertexBuffer._NormalKind;
  14031. },
  14032. enumerable: true,
  14033. configurable: true
  14034. });
  14035. Object.defineProperty(VertexBuffer, "UVKind", {
  14036. get: function () {
  14037. return VertexBuffer._UVKind;
  14038. },
  14039. enumerable: true,
  14040. configurable: true
  14041. });
  14042. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14043. get: function () {
  14044. return VertexBuffer._UV2Kind;
  14045. },
  14046. enumerable: true,
  14047. configurable: true
  14048. });
  14049. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14050. get: function () {
  14051. return VertexBuffer._UV3Kind;
  14052. },
  14053. enumerable: true,
  14054. configurable: true
  14055. });
  14056. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14057. get: function () {
  14058. return VertexBuffer._UV4Kind;
  14059. },
  14060. enumerable: true,
  14061. configurable: true
  14062. });
  14063. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14064. get: function () {
  14065. return VertexBuffer._UV5Kind;
  14066. },
  14067. enumerable: true,
  14068. configurable: true
  14069. });
  14070. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14071. get: function () {
  14072. return VertexBuffer._UV6Kind;
  14073. },
  14074. enumerable: true,
  14075. configurable: true
  14076. });
  14077. Object.defineProperty(VertexBuffer, "ColorKind", {
  14078. get: function () {
  14079. return VertexBuffer._ColorKind;
  14080. },
  14081. enumerable: true,
  14082. configurable: true
  14083. });
  14084. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14085. get: function () {
  14086. return VertexBuffer._MatricesIndicesKind;
  14087. },
  14088. enumerable: true,
  14089. configurable: true
  14090. });
  14091. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14092. get: function () {
  14093. return VertexBuffer._MatricesWeightsKind;
  14094. },
  14095. enumerable: true,
  14096. configurable: true
  14097. });
  14098. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14099. get: function () {
  14100. return VertexBuffer._MatricesIndicesExtraKind;
  14101. },
  14102. enumerable: true,
  14103. configurable: true
  14104. });
  14105. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14106. get: function () {
  14107. return VertexBuffer._MatricesWeightsExtraKind;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. // Enums
  14113. VertexBuffer._PositionKind = "position";
  14114. VertexBuffer._NormalKind = "normal";
  14115. VertexBuffer._UVKind = "uv";
  14116. VertexBuffer._UV2Kind = "uv2";
  14117. VertexBuffer._UV3Kind = "uv3";
  14118. VertexBuffer._UV4Kind = "uv4";
  14119. VertexBuffer._UV5Kind = "uv5";
  14120. VertexBuffer._UV6Kind = "uv6";
  14121. VertexBuffer._ColorKind = "color";
  14122. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14123. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14124. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14125. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14126. return VertexBuffer;
  14127. })();
  14128. BABYLON.VertexBuffer = VertexBuffer;
  14129. })(BABYLON || (BABYLON = {}));
  14130. var BABYLON;
  14131. (function (BABYLON) {
  14132. /**
  14133. * Creates an instance based on a source mesh.
  14134. */
  14135. var InstancedMesh = (function (_super) {
  14136. __extends(InstancedMesh, _super);
  14137. function InstancedMesh(name, source) {
  14138. _super.call(this, name, source.getScene());
  14139. source.instances.push(this);
  14140. this._sourceMesh = source;
  14141. this.position.copyFrom(source.position);
  14142. this.rotation.copyFrom(source.rotation);
  14143. this.scaling.copyFrom(source.scaling);
  14144. if (source.rotationQuaternion) {
  14145. this.rotationQuaternion = source.rotationQuaternion.clone();
  14146. }
  14147. this.infiniteDistance = source.infiniteDistance;
  14148. this.setPivotMatrix(source.getPivotMatrix());
  14149. this.refreshBoundingInfo();
  14150. this._syncSubMeshes();
  14151. }
  14152. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14153. // Methods
  14154. get: function () {
  14155. return this._sourceMesh.receiveShadows;
  14156. },
  14157. enumerable: true,
  14158. configurable: true
  14159. });
  14160. Object.defineProperty(InstancedMesh.prototype, "material", {
  14161. get: function () {
  14162. return this._sourceMesh.material;
  14163. },
  14164. enumerable: true,
  14165. configurable: true
  14166. });
  14167. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14168. get: function () {
  14169. return this._sourceMesh.visibility;
  14170. },
  14171. enumerable: true,
  14172. configurable: true
  14173. });
  14174. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14175. get: function () {
  14176. return this._sourceMesh.skeleton;
  14177. },
  14178. enumerable: true,
  14179. configurable: true
  14180. });
  14181. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14182. get: function () {
  14183. return this._sourceMesh.renderingGroupId;
  14184. },
  14185. enumerable: true,
  14186. configurable: true
  14187. });
  14188. InstancedMesh.prototype.getTotalVertices = function () {
  14189. return this._sourceMesh.getTotalVertices();
  14190. };
  14191. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14192. get: function () {
  14193. return this._sourceMesh;
  14194. },
  14195. enumerable: true,
  14196. configurable: true
  14197. });
  14198. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14199. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14200. };
  14201. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14202. return this._sourceMesh.isVerticesDataPresent(kind);
  14203. };
  14204. InstancedMesh.prototype.getIndices = function () {
  14205. return this._sourceMesh.getIndices();
  14206. };
  14207. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14208. get: function () {
  14209. return this._sourceMesh._positions;
  14210. },
  14211. enumerable: true,
  14212. configurable: true
  14213. });
  14214. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14215. var meshBB = this._sourceMesh.getBoundingInfo();
  14216. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14217. this._updateBoundingInfo();
  14218. };
  14219. InstancedMesh.prototype._preActivate = function () {
  14220. if (this._currentLOD) {
  14221. this._currentLOD._preActivate();
  14222. }
  14223. };
  14224. InstancedMesh.prototype._activate = function (renderId) {
  14225. if (this._currentLOD) {
  14226. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14227. }
  14228. };
  14229. InstancedMesh.prototype.getLOD = function (camera) {
  14230. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14231. if (this._currentLOD === this.sourceMesh) {
  14232. return this;
  14233. }
  14234. return this._currentLOD;
  14235. };
  14236. InstancedMesh.prototype._syncSubMeshes = function () {
  14237. this.releaseSubMeshes();
  14238. if (this._sourceMesh.subMeshes) {
  14239. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14240. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14241. }
  14242. }
  14243. };
  14244. InstancedMesh.prototype._generatePointsArray = function () {
  14245. return this._sourceMesh._generatePointsArray();
  14246. };
  14247. // Clone
  14248. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14249. var result = this._sourceMesh.createInstance(name);
  14250. // Deep copy
  14251. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14252. // Bounding info
  14253. this.refreshBoundingInfo();
  14254. // Parent
  14255. if (newParent) {
  14256. result.parent = newParent;
  14257. }
  14258. if (!doNotCloneChildren) {
  14259. // Children
  14260. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14261. var mesh = this.getScene().meshes[index];
  14262. if (mesh.parent === this) {
  14263. mesh.clone(mesh.name, result);
  14264. }
  14265. }
  14266. }
  14267. result.computeWorldMatrix(true);
  14268. return result;
  14269. };
  14270. // Dispoe
  14271. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14272. // Remove from mesh
  14273. var index = this._sourceMesh.instances.indexOf(this);
  14274. this._sourceMesh.instances.splice(index, 1);
  14275. _super.prototype.dispose.call(this, doNotRecurse);
  14276. };
  14277. return InstancedMesh;
  14278. })(BABYLON.AbstractMesh);
  14279. BABYLON.InstancedMesh = InstancedMesh;
  14280. })(BABYLON || (BABYLON = {}));
  14281. var BABYLON;
  14282. (function (BABYLON) {
  14283. var _InstancesBatch = (function () {
  14284. function _InstancesBatch() {
  14285. this.mustReturn = false;
  14286. this.visibleInstances = new Array();
  14287. this.renderSelf = new Array();
  14288. }
  14289. return _InstancesBatch;
  14290. })();
  14291. BABYLON._InstancesBatch = _InstancesBatch;
  14292. var Mesh = (function (_super) {
  14293. __extends(Mesh, _super);
  14294. /**
  14295. * @constructor
  14296. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14297. * @param {Scene} scene - The scene to add this mesh to.
  14298. * @param {Node} parent - The parent of this mesh, if it has one
  14299. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14300. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14301. * When false, achieved by calling a clone(), also passing False.
  14302. * This will make creation of children, recursive.
  14303. */
  14304. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14305. if (parent === void 0) { parent = null; }
  14306. _super.call(this, name, scene);
  14307. // Members
  14308. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14309. this.instances = new Array();
  14310. this._LODLevels = new Array();
  14311. this._onBeforeRenderCallbacks = new Array();
  14312. this._onAfterRenderCallbacks = new Array();
  14313. this._visibleInstances = {};
  14314. this._renderIdForInstances = new Array();
  14315. this._batchCache = new _InstancesBatch();
  14316. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14317. this._sideOrientation = Mesh._DEFAULTSIDE;
  14318. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14319. if (source) {
  14320. // Geometry
  14321. if (source._geometry) {
  14322. source._geometry.applyToMesh(this);
  14323. }
  14324. // Deep copy
  14325. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14326. this.id = name + "." + source.id;
  14327. // Material
  14328. this.material = source.material;
  14329. var index;
  14330. if (!doNotCloneChildren) {
  14331. // Children
  14332. for (index = 0; index < scene.meshes.length; index++) {
  14333. var mesh = scene.meshes[index];
  14334. if (mesh.parent === source) {
  14335. // doNotCloneChildren is always going to be False
  14336. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14337. }
  14338. }
  14339. }
  14340. // Particles
  14341. for (index = 0; index < scene.particleSystems.length; index++) {
  14342. var system = scene.particleSystems[index];
  14343. if (system.emitter === source) {
  14344. system.clone(system.name, this);
  14345. }
  14346. }
  14347. this.computeWorldMatrix(true);
  14348. }
  14349. // Parent
  14350. if (parent !== null) {
  14351. this.parent = parent;
  14352. }
  14353. }
  14354. Object.defineProperty(Mesh, "FRONTSIDE", {
  14355. get: function () {
  14356. return Mesh._FRONTSIDE;
  14357. },
  14358. enumerable: true,
  14359. configurable: true
  14360. });
  14361. Object.defineProperty(Mesh, "BACKSIDE", {
  14362. get: function () {
  14363. return Mesh._BACKSIDE;
  14364. },
  14365. enumerable: true,
  14366. configurable: true
  14367. });
  14368. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14369. get: function () {
  14370. return Mesh._DOUBLESIDE;
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14376. get: function () {
  14377. return Mesh._DEFAULTSIDE;
  14378. },
  14379. enumerable: true,
  14380. configurable: true
  14381. });
  14382. Object.defineProperty(Mesh, "NO_CAP", {
  14383. get: function () {
  14384. return Mesh._NO_CAP;
  14385. },
  14386. enumerable: true,
  14387. configurable: true
  14388. });
  14389. Object.defineProperty(Mesh, "CAP_START", {
  14390. get: function () {
  14391. return Mesh._CAP_START;
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. Object.defineProperty(Mesh, "CAP_END", {
  14397. get: function () {
  14398. return Mesh._CAP_END;
  14399. },
  14400. enumerable: true,
  14401. configurable: true
  14402. });
  14403. Object.defineProperty(Mesh, "CAP_ALL", {
  14404. get: function () {
  14405. return Mesh._CAP_ALL;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14411. // Methods
  14412. get: function () {
  14413. return this._LODLevels.length > 0;
  14414. },
  14415. enumerable: true,
  14416. configurable: true
  14417. });
  14418. Mesh.prototype._sortLODLevels = function () {
  14419. this._LODLevels.sort(function (a, b) {
  14420. if (a.distance < b.distance) {
  14421. return 1;
  14422. }
  14423. if (a.distance > b.distance) {
  14424. return -1;
  14425. }
  14426. return 0;
  14427. });
  14428. };
  14429. /**
  14430. * Add a mesh as LOD level triggered at the given distance.
  14431. * @param {number} distance - the distance from the center of the object to show this level
  14432. * @param {Mesh} mesh - the mesh to be added as LOD level
  14433. * @return {Mesh} this mesh (for chaining)
  14434. */
  14435. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14436. if (mesh && mesh._masterMesh) {
  14437. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14438. return this;
  14439. }
  14440. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14441. this._LODLevels.push(level);
  14442. if (mesh) {
  14443. mesh._masterMesh = this;
  14444. }
  14445. this._sortLODLevels();
  14446. return this;
  14447. };
  14448. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14449. for (var index = 0; index < this._LODLevels.length; index++) {
  14450. var level = this._LODLevels[index];
  14451. if (level.distance === distance) {
  14452. return level.mesh;
  14453. }
  14454. }
  14455. return null;
  14456. };
  14457. /**
  14458. * Remove a mesh from the LOD array
  14459. * @param {Mesh} mesh - the mesh to be removed.
  14460. * @return {Mesh} this mesh (for chaining)
  14461. */
  14462. Mesh.prototype.removeLODLevel = function (mesh) {
  14463. for (var index = 0; index < this._LODLevels.length; index++) {
  14464. if (this._LODLevels[index].mesh === mesh) {
  14465. this._LODLevels.splice(index, 1);
  14466. if (mesh) {
  14467. mesh._masterMesh = null;
  14468. }
  14469. }
  14470. }
  14471. this._sortLODLevels();
  14472. return this;
  14473. };
  14474. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14475. if (!this._LODLevels || this._LODLevels.length === 0) {
  14476. return this;
  14477. }
  14478. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14479. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14480. if (this.onLODLevelSelection) {
  14481. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14482. }
  14483. return this;
  14484. }
  14485. for (var index = 0; index < this._LODLevels.length; index++) {
  14486. var level = this._LODLevels[index];
  14487. if (level.distance < distanceToCamera) {
  14488. if (level.mesh) {
  14489. level.mesh._preActivate();
  14490. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14491. }
  14492. if (this.onLODLevelSelection) {
  14493. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14494. }
  14495. return level.mesh;
  14496. }
  14497. }
  14498. if (this.onLODLevelSelection) {
  14499. this.onLODLevelSelection(distanceToCamera, this, this);
  14500. }
  14501. return this;
  14502. };
  14503. Object.defineProperty(Mesh.prototype, "geometry", {
  14504. get: function () {
  14505. return this._geometry;
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Mesh.prototype.getTotalVertices = function () {
  14511. if (!this._geometry) {
  14512. return 0;
  14513. }
  14514. return this._geometry.getTotalVertices();
  14515. };
  14516. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14517. if (!this._geometry) {
  14518. return null;
  14519. }
  14520. return this._geometry.getVerticesData(kind, copyWhenShared);
  14521. };
  14522. Mesh.prototype.getVertexBuffer = function (kind) {
  14523. if (!this._geometry) {
  14524. return undefined;
  14525. }
  14526. return this._geometry.getVertexBuffer(kind);
  14527. };
  14528. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14529. if (!this._geometry) {
  14530. if (this._delayInfo) {
  14531. return this._delayInfo.indexOf(kind) !== -1;
  14532. }
  14533. return false;
  14534. }
  14535. return this._geometry.isVerticesDataPresent(kind);
  14536. };
  14537. Mesh.prototype.getVerticesDataKinds = function () {
  14538. if (!this._geometry) {
  14539. var result = [];
  14540. if (this._delayInfo) {
  14541. for (var kind in this._delayInfo) {
  14542. result.push(kind);
  14543. }
  14544. }
  14545. return result;
  14546. }
  14547. return this._geometry.getVerticesDataKinds();
  14548. };
  14549. Mesh.prototype.getTotalIndices = function () {
  14550. if (!this._geometry) {
  14551. return 0;
  14552. }
  14553. return this._geometry.getTotalIndices();
  14554. };
  14555. Mesh.prototype.getIndices = function (copyWhenShared) {
  14556. if (!this._geometry) {
  14557. return [];
  14558. }
  14559. return this._geometry.getIndices(copyWhenShared);
  14560. };
  14561. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14562. get: function () {
  14563. return this._masterMesh !== null && this._masterMesh !== undefined;
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Mesh.prototype.isReady = function () {
  14569. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14570. return false;
  14571. }
  14572. return _super.prototype.isReady.call(this);
  14573. };
  14574. Mesh.prototype.isDisposed = function () {
  14575. return this._isDisposed;
  14576. };
  14577. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14578. get: function () {
  14579. return this._sideOrientation;
  14580. },
  14581. set: function (sideO) {
  14582. this._sideOrientation = sideO;
  14583. },
  14584. enumerable: true,
  14585. configurable: true
  14586. });
  14587. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14588. get: function () {
  14589. return this._areNormalsFrozen;
  14590. },
  14591. enumerable: true,
  14592. configurable: true
  14593. });
  14594. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14595. Mesh.prototype.freezeNormals = function () {
  14596. this._areNormalsFrozen = true;
  14597. };
  14598. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14599. Mesh.prototype.unfreezeNormals = function () {
  14600. this._areNormalsFrozen = false;
  14601. };
  14602. // Methods
  14603. Mesh.prototype._preActivate = function () {
  14604. var sceneRenderId = this.getScene().getRenderId();
  14605. if (this._preActivateId === sceneRenderId) {
  14606. return;
  14607. }
  14608. this._preActivateId = sceneRenderId;
  14609. this._visibleInstances = null;
  14610. };
  14611. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14612. if (!this._visibleInstances) {
  14613. this._visibleInstances = {};
  14614. this._visibleInstances.defaultRenderId = renderId;
  14615. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14616. }
  14617. if (!this._visibleInstances[renderId]) {
  14618. this._visibleInstances[renderId] = new Array();
  14619. }
  14620. this._visibleInstances[renderId].push(instance);
  14621. };
  14622. Mesh.prototype.refreshBoundingInfo = function () {
  14623. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14624. if (data) {
  14625. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14626. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14627. }
  14628. if (this.subMeshes) {
  14629. for (var index = 0; index < this.subMeshes.length; index++) {
  14630. this.subMeshes[index].refreshBoundingInfo();
  14631. }
  14632. }
  14633. this._updateBoundingInfo();
  14634. };
  14635. Mesh.prototype._createGlobalSubMesh = function () {
  14636. var totalVertices = this.getTotalVertices();
  14637. if (!totalVertices || !this.getIndices()) {
  14638. return null;
  14639. }
  14640. this.releaseSubMeshes();
  14641. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14642. };
  14643. Mesh.prototype.subdivide = function (count) {
  14644. if (count < 1) {
  14645. return;
  14646. }
  14647. var totalIndices = this.getTotalIndices();
  14648. var subdivisionSize = (totalIndices / count) | 0;
  14649. var offset = 0;
  14650. // Ensure that subdivisionSize is a multiple of 3
  14651. while (subdivisionSize % 3 !== 0) {
  14652. subdivisionSize++;
  14653. }
  14654. this.releaseSubMeshes();
  14655. for (var index = 0; index < count; index++) {
  14656. if (offset >= totalIndices) {
  14657. break;
  14658. }
  14659. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14660. offset += subdivisionSize;
  14661. }
  14662. this.synchronizeInstances();
  14663. };
  14664. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14665. if (!this._geometry) {
  14666. var vertexData = new BABYLON.VertexData();
  14667. vertexData.set(data, kind);
  14668. var scene = this.getScene();
  14669. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14670. }
  14671. else {
  14672. this._geometry.setVerticesData(kind, data, updatable, stride);
  14673. }
  14674. };
  14675. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14676. if (!this._geometry) {
  14677. return;
  14678. }
  14679. if (!makeItUnique) {
  14680. this._geometry.updateVerticesData(kind, data, updateExtends);
  14681. }
  14682. else {
  14683. this.makeGeometryUnique();
  14684. this.updateVerticesData(kind, data, updateExtends, false);
  14685. }
  14686. };
  14687. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14688. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14689. if (!this._geometry) {
  14690. return;
  14691. }
  14692. if (!makeItUnique) {
  14693. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14694. }
  14695. else {
  14696. this.makeGeometryUnique();
  14697. this.updateVerticesDataDirectly(kind, data, offset, false);
  14698. }
  14699. };
  14700. // Mesh positions update function :
  14701. // updates the mesh positions according to the positionFunction returned values.
  14702. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14703. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14704. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14705. if (computeNormals === void 0) { computeNormals = true; }
  14706. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14707. positionFunction(positions);
  14708. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14709. if (computeNormals) {
  14710. var indices = this.getIndices();
  14711. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14712. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14713. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14714. }
  14715. };
  14716. Mesh.prototype.makeGeometryUnique = function () {
  14717. if (!this._geometry) {
  14718. return;
  14719. }
  14720. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14721. geometry.applyToMesh(this);
  14722. };
  14723. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14724. if (!this._geometry) {
  14725. var vertexData = new BABYLON.VertexData();
  14726. vertexData.indices = indices;
  14727. var scene = this.getScene();
  14728. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14729. }
  14730. else {
  14731. this._geometry.setIndices(indices, totalVertices);
  14732. }
  14733. };
  14734. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14735. var engine = this.getScene().getEngine();
  14736. // Wireframe
  14737. var indexToBind;
  14738. switch (fillMode) {
  14739. case BABYLON.Material.PointFillMode:
  14740. indexToBind = null;
  14741. break;
  14742. case BABYLON.Material.WireFrameFillMode:
  14743. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14744. break;
  14745. default:
  14746. case BABYLON.Material.TriangleFillMode:
  14747. indexToBind = this._geometry.getIndexBuffer();
  14748. break;
  14749. }
  14750. // VBOs
  14751. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14752. };
  14753. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14754. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14755. return;
  14756. }
  14757. var engine = this.getScene().getEngine();
  14758. // Draw order
  14759. switch (fillMode) {
  14760. case BABYLON.Material.PointFillMode:
  14761. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14762. break;
  14763. case BABYLON.Material.WireFrameFillMode:
  14764. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14765. break;
  14766. default:
  14767. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14768. }
  14769. };
  14770. Mesh.prototype.registerBeforeRender = function (func) {
  14771. this._onBeforeRenderCallbacks.push(func);
  14772. };
  14773. Mesh.prototype.unregisterBeforeRender = function (func) {
  14774. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14775. if (index > -1) {
  14776. this._onBeforeRenderCallbacks.splice(index, 1);
  14777. }
  14778. };
  14779. Mesh.prototype.registerAfterRender = function (func) {
  14780. this._onAfterRenderCallbacks.push(func);
  14781. };
  14782. Mesh.prototype.unregisterAfterRender = function (func) {
  14783. var index = this._onAfterRenderCallbacks.indexOf(func);
  14784. if (index > -1) {
  14785. this._onAfterRenderCallbacks.splice(index, 1);
  14786. }
  14787. };
  14788. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14789. var scene = this.getScene();
  14790. this._batchCache.mustReturn = false;
  14791. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14792. this._batchCache.visibleInstances[subMeshId] = null;
  14793. if (this._visibleInstances) {
  14794. var currentRenderId = scene.getRenderId();
  14795. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14796. var selfRenderId = this._renderId;
  14797. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14798. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14799. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14800. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14801. }
  14802. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14803. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14804. this._batchCache.mustReturn = true;
  14805. return this._batchCache;
  14806. }
  14807. if (currentRenderId !== selfRenderId) {
  14808. this._batchCache.renderSelf[subMeshId] = false;
  14809. }
  14810. }
  14811. this._renderIdForInstances[subMeshId] = currentRenderId;
  14812. }
  14813. return this._batchCache;
  14814. };
  14815. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14816. var visibleInstances = batch.visibleInstances[subMesh._id];
  14817. var matricesCount = visibleInstances.length + 1;
  14818. var bufferSize = matricesCount * 16 * 4;
  14819. while (this._instancesBufferSize < bufferSize) {
  14820. this._instancesBufferSize *= 2;
  14821. }
  14822. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14823. if (this._worldMatricesInstancesBuffer) {
  14824. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14825. }
  14826. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14827. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14828. }
  14829. var offset = 0;
  14830. var instancesCount = 0;
  14831. var world = this.getWorldMatrix();
  14832. if (batch.renderSelf[subMesh._id]) {
  14833. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14834. offset += 16;
  14835. instancesCount++;
  14836. }
  14837. if (visibleInstances) {
  14838. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14839. var instance = visibleInstances[instanceIndex];
  14840. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14841. offset += 16;
  14842. instancesCount++;
  14843. }
  14844. }
  14845. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14846. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14847. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14848. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14849. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14850. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14851. this._draw(subMesh, fillMode, instancesCount);
  14852. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14853. };
  14854. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14855. var scene = this.getScene();
  14856. var engine = scene.getEngine();
  14857. if (hardwareInstancedRendering) {
  14858. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14859. }
  14860. else {
  14861. if (batch.renderSelf[subMesh._id]) {
  14862. // Draw
  14863. if (onBeforeDraw) {
  14864. onBeforeDraw(false, this.getWorldMatrix());
  14865. }
  14866. this._draw(subMesh, fillMode);
  14867. }
  14868. if (batch.visibleInstances[subMesh._id]) {
  14869. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14870. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14871. // World
  14872. var world = instance.getWorldMatrix();
  14873. if (onBeforeDraw) {
  14874. onBeforeDraw(true, world);
  14875. }
  14876. // Draw
  14877. this._draw(subMesh, fillMode);
  14878. }
  14879. }
  14880. }
  14881. };
  14882. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14883. var scene = this.getScene();
  14884. // Managing instances
  14885. var batch = this._getInstancesRenderList(subMesh._id);
  14886. if (batch.mustReturn) {
  14887. return;
  14888. }
  14889. // Checking geometry state
  14890. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14891. return;
  14892. }
  14893. var callbackIndex;
  14894. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14895. this._onBeforeRenderCallbacks[callbackIndex](this);
  14896. }
  14897. var engine = scene.getEngine();
  14898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14899. // Material
  14900. var effectiveMaterial = subMesh.getMaterial();
  14901. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14902. return;
  14903. }
  14904. // Outline - step 1
  14905. var savedDepthWrite = engine.getDepthWrite();
  14906. if (this.renderOutline) {
  14907. engine.setDepthWrite(false);
  14908. scene.getOutlineRenderer().render(subMesh, batch);
  14909. engine.setDepthWrite(savedDepthWrite);
  14910. }
  14911. effectiveMaterial._preBind();
  14912. var effect = effectiveMaterial.getEffect();
  14913. // Bind
  14914. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14915. this._bind(subMesh, effect, fillMode);
  14916. var world = this.getWorldMatrix();
  14917. effectiveMaterial.bind(world, this);
  14918. // Alpha mode
  14919. if (enableAlphaMode) {
  14920. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14921. }
  14922. // Draw
  14923. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14924. if (isInstance) {
  14925. effectiveMaterial.bindOnlyWorldMatrix(world);
  14926. }
  14927. });
  14928. // Unbind
  14929. effectiveMaterial.unbind();
  14930. // Outline - step 2
  14931. if (this.renderOutline && savedDepthWrite) {
  14932. engine.setDepthWrite(true);
  14933. engine.setColorWrite(false);
  14934. scene.getOutlineRenderer().render(subMesh, batch);
  14935. engine.setColorWrite(true);
  14936. }
  14937. // Overlay
  14938. if (this.renderOverlay) {
  14939. var currentMode = engine.getAlphaMode();
  14940. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14941. scene.getOutlineRenderer().render(subMesh, batch, true);
  14942. engine.setAlphaMode(currentMode);
  14943. }
  14944. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14945. this._onAfterRenderCallbacks[callbackIndex](this);
  14946. }
  14947. };
  14948. Mesh.prototype.getEmittedParticleSystems = function () {
  14949. var results = new Array();
  14950. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14951. var particleSystem = this.getScene().particleSystems[index];
  14952. if (particleSystem.emitter === this) {
  14953. results.push(particleSystem);
  14954. }
  14955. }
  14956. return results;
  14957. };
  14958. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14959. var results = new Array();
  14960. var descendants = this.getDescendants();
  14961. descendants.push(this);
  14962. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14963. var particleSystem = this.getScene().particleSystems[index];
  14964. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14965. results.push(particleSystem);
  14966. }
  14967. }
  14968. return results;
  14969. };
  14970. Mesh.prototype.getChildren = function () {
  14971. var results = [];
  14972. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14973. var mesh = this.getScene().meshes[index];
  14974. if (mesh.parent === this) {
  14975. results.push(mesh);
  14976. }
  14977. }
  14978. return results;
  14979. };
  14980. Mesh.prototype._checkDelayState = function () {
  14981. var _this = this;
  14982. var that = this;
  14983. var scene = this.getScene();
  14984. if (this._geometry) {
  14985. this._geometry.load(scene);
  14986. }
  14987. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14988. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14989. scene._addPendingData(that);
  14990. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14991. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14992. if (data instanceof ArrayBuffer) {
  14993. _this._delayLoadingFunction(data, _this);
  14994. }
  14995. else {
  14996. _this._delayLoadingFunction(JSON.parse(data), _this);
  14997. }
  14998. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14999. scene._removePendingData(_this);
  15000. }, function () { }, scene.database, getBinaryData);
  15001. }
  15002. };
  15003. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15004. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15005. return false;
  15006. }
  15007. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15008. return false;
  15009. }
  15010. this._checkDelayState();
  15011. return true;
  15012. };
  15013. Mesh.prototype.setMaterialByID = function (id) {
  15014. var materials = this.getScene().materials;
  15015. var index;
  15016. for (index = 0; index < materials.length; index++) {
  15017. if (materials[index].id === id) {
  15018. this.material = materials[index];
  15019. return;
  15020. }
  15021. }
  15022. // Multi
  15023. var multiMaterials = this.getScene().multiMaterials;
  15024. for (index = 0; index < multiMaterials.length; index++) {
  15025. if (multiMaterials[index].id === id) {
  15026. this.material = multiMaterials[index];
  15027. return;
  15028. }
  15029. }
  15030. };
  15031. Mesh.prototype.getAnimatables = function () {
  15032. var results = [];
  15033. if (this.material) {
  15034. results.push(this.material);
  15035. }
  15036. if (this.skeleton) {
  15037. results.push(this.skeleton);
  15038. }
  15039. return results;
  15040. };
  15041. // Geometry
  15042. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15043. // Position
  15044. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15045. return;
  15046. }
  15047. this._resetPointsArrayCache();
  15048. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15049. var temp = [];
  15050. var index;
  15051. for (index = 0; index < data.length; index += 3) {
  15052. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15053. }
  15054. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15055. // Normals
  15056. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15057. return;
  15058. }
  15059. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15060. temp = [];
  15061. for (index = 0; index < data.length; index += 3) {
  15062. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15063. }
  15064. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15065. // flip faces?
  15066. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15067. this.flipFaces();
  15068. }
  15069. };
  15070. // Will apply current transform to mesh and reset world matrix
  15071. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15072. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15073. this.scaling.copyFromFloats(1, 1, 1);
  15074. this.position.copyFromFloats(0, 0, 0);
  15075. this.rotation.copyFromFloats(0, 0, 0);
  15076. //only if quaternion is already set
  15077. if (this.rotationQuaternion) {
  15078. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15079. }
  15080. this._worldMatrix = BABYLON.Matrix.Identity();
  15081. };
  15082. // Cache
  15083. Mesh.prototype._resetPointsArrayCache = function () {
  15084. this._positions = null;
  15085. };
  15086. Mesh.prototype._generatePointsArray = function () {
  15087. if (this._positions)
  15088. return true;
  15089. this._positions = [];
  15090. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15091. if (!data) {
  15092. return false;
  15093. }
  15094. for (var index = 0; index < data.length; index += 3) {
  15095. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15096. }
  15097. return true;
  15098. };
  15099. // Clone
  15100. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15101. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15102. };
  15103. // Dispose
  15104. Mesh.prototype.dispose = function (doNotRecurse) {
  15105. if (this._geometry) {
  15106. this._geometry.releaseForMesh(this, true);
  15107. }
  15108. // Instances
  15109. if (this._worldMatricesInstancesBuffer) {
  15110. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15111. this._worldMatricesInstancesBuffer = null;
  15112. }
  15113. while (this.instances.length) {
  15114. this.instances[0].dispose();
  15115. }
  15116. _super.prototype.dispose.call(this, doNotRecurse);
  15117. };
  15118. // Geometric tools
  15119. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15120. var _this = this;
  15121. var scene = this.getScene();
  15122. var onload = function (img) {
  15123. // Getting height map data
  15124. var canvas = document.createElement("canvas");
  15125. var context = canvas.getContext("2d");
  15126. var heightMapWidth = img.width;
  15127. var heightMapHeight = img.height;
  15128. canvas.width = heightMapWidth;
  15129. canvas.height = heightMapHeight;
  15130. context.drawImage(img, 0, 0);
  15131. // Create VertexData from map data
  15132. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15133. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15134. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15135. //execute success callback, if set
  15136. if (onSuccess) {
  15137. onSuccess(_this);
  15138. }
  15139. };
  15140. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15141. };
  15142. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15143. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15144. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15145. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15146. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15147. return;
  15148. }
  15149. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15150. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15151. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15152. var position = BABYLON.Vector3.Zero();
  15153. var normal = BABYLON.Vector3.Zero();
  15154. var uv = BABYLON.Vector2.Zero();
  15155. for (var index = 0; index < positions.length; index += 3) {
  15156. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15157. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15158. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15159. // Compute height
  15160. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15161. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15162. var pos = (u + v * heightMapWidth) * 4;
  15163. var r = buffer[pos] / 255.0;
  15164. var g = buffer[pos + 1] / 255.0;
  15165. var b = buffer[pos + 2] / 255.0;
  15166. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15167. normal.normalize();
  15168. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15169. position = position.add(normal);
  15170. position.toArray(positions, index);
  15171. }
  15172. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15173. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15174. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15175. };
  15176. Mesh.prototype.convertToFlatShadedMesh = function () {
  15177. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15178. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15179. var kinds = this.getVerticesDataKinds();
  15180. var vbs = [];
  15181. var data = [];
  15182. var newdata = [];
  15183. var updatableNormals = false;
  15184. var kindIndex;
  15185. var kind;
  15186. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15187. kind = kinds[kindIndex];
  15188. var vertexBuffer = this.getVertexBuffer(kind);
  15189. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15190. updatableNormals = vertexBuffer.isUpdatable();
  15191. kinds.splice(kindIndex, 1);
  15192. kindIndex--;
  15193. continue;
  15194. }
  15195. vbs[kind] = vertexBuffer;
  15196. data[kind] = vbs[kind].getData();
  15197. newdata[kind] = [];
  15198. }
  15199. // Save previous submeshes
  15200. var previousSubmeshes = this.subMeshes.slice(0);
  15201. var indices = this.getIndices();
  15202. var totalIndices = this.getTotalIndices();
  15203. // Generating unique vertices per face
  15204. var index;
  15205. for (index = 0; index < totalIndices; index++) {
  15206. var vertexIndex = indices[index];
  15207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15208. kind = kinds[kindIndex];
  15209. var stride = vbs[kind].getStrideSize();
  15210. for (var offset = 0; offset < stride; offset++) {
  15211. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15212. }
  15213. }
  15214. }
  15215. // Updating faces & normal
  15216. var normals = [];
  15217. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15218. for (index = 0; index < totalIndices; index += 3) {
  15219. indices[index] = index;
  15220. indices[index + 1] = index + 1;
  15221. indices[index + 2] = index + 2;
  15222. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15223. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15224. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15225. var p1p2 = p1.subtract(p2);
  15226. var p3p2 = p3.subtract(p2);
  15227. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15228. // Store same normals for every vertex
  15229. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15230. normals.push(normal.x);
  15231. normals.push(normal.y);
  15232. normals.push(normal.z);
  15233. }
  15234. }
  15235. this.setIndices(indices);
  15236. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15237. // Updating vertex buffers
  15238. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15239. kind = kinds[kindIndex];
  15240. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15241. }
  15242. // Updating submeshes
  15243. this.releaseSubMeshes();
  15244. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15245. var previousOne = previousSubmeshes[submeshIndex];
  15246. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15247. }
  15248. this.synchronizeInstances();
  15249. };
  15250. // will inverse faces orientations, and invert normals too if specified
  15251. Mesh.prototype.flipFaces = function (flipNormals) {
  15252. if (flipNormals === void 0) { flipNormals = false; }
  15253. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15254. var i;
  15255. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15256. for (i = 0; i < vertex_data.normals.length; i++) {
  15257. vertex_data.normals[i] *= -1;
  15258. }
  15259. }
  15260. var temp;
  15261. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15262. // reassign indices
  15263. temp = vertex_data.indices[i + 1];
  15264. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15265. vertex_data.indices[i + 2] = temp;
  15266. }
  15267. vertex_data.applyToMesh(this);
  15268. };
  15269. // Instances
  15270. Mesh.prototype.createInstance = function (name) {
  15271. return new BABYLON.InstancedMesh(name, this);
  15272. };
  15273. Mesh.prototype.synchronizeInstances = function () {
  15274. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15275. var instance = this.instances[instanceIndex];
  15276. instance._syncSubMeshes();
  15277. }
  15278. };
  15279. /**
  15280. * Simplify the mesh according to the given array of settings.
  15281. * Function will return immediately and will simplify async.
  15282. * @param settings a collection of simplification settings.
  15283. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15284. * @param type the type of simplification to run.
  15285. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15286. */
  15287. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15288. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15289. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15290. this.getScene().simplificationQueue.addTask({
  15291. settings: settings,
  15292. parallelProcessing: parallelProcessing,
  15293. mesh: this,
  15294. simplificationType: simplificationType,
  15295. successCallback: successCallback
  15296. });
  15297. };
  15298. /**
  15299. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15300. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15301. * This should be used together with the simplification to avoid disappearing triangles.
  15302. * @param successCallback an optional success callback to be called after the optimization finished.
  15303. */
  15304. Mesh.prototype.optimizeIndices = function (successCallback) {
  15305. var _this = this;
  15306. var indices = this.getIndices();
  15307. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15308. var vectorPositions = [];
  15309. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15310. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15311. }
  15312. var dupes = [];
  15313. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15314. var realPos = vectorPositions.length - 1 - iteration;
  15315. var testedPosition = vectorPositions[realPos];
  15316. for (var j = 0; j < realPos; ++j) {
  15317. var againstPosition = vectorPositions[j];
  15318. if (testedPosition.equals(againstPosition)) {
  15319. dupes[realPos] = j;
  15320. break;
  15321. }
  15322. }
  15323. }, function () {
  15324. for (var i = 0; i < indices.length; ++i) {
  15325. indices[i] = dupes[indices[i]] || indices[i];
  15326. }
  15327. //indices are now reordered
  15328. var originalSubMeshes = _this.subMeshes.slice(0);
  15329. _this.setIndices(indices);
  15330. _this.subMeshes = originalSubMeshes;
  15331. if (successCallback) {
  15332. successCallback(_this);
  15333. }
  15334. });
  15335. };
  15336. // Statics
  15337. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15338. var mesh = new Mesh(parsedMesh.name, scene);
  15339. mesh.id = parsedMesh.id;
  15340. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15341. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15342. if (parsedMesh.rotationQuaternion) {
  15343. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15344. }
  15345. else if (parsedMesh.rotation) {
  15346. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15347. }
  15348. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15349. if (parsedMesh.localMatrix) {
  15350. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15351. }
  15352. else if (parsedMesh.pivotMatrix) {
  15353. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15354. }
  15355. mesh.setEnabled(parsedMesh.isEnabled);
  15356. mesh.isVisible = parsedMesh.isVisible;
  15357. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15358. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15359. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15360. if (parsedMesh.applyFog !== undefined) {
  15361. mesh.applyFog = parsedMesh.applyFog;
  15362. }
  15363. if (parsedMesh.pickable !== undefined) {
  15364. mesh.isPickable = parsedMesh.pickable;
  15365. }
  15366. if (parsedMesh.alphaIndex !== undefined) {
  15367. mesh.alphaIndex = parsedMesh.alphaIndex;
  15368. }
  15369. mesh.receiveShadows = parsedMesh.receiveShadows;
  15370. mesh.billboardMode = parsedMesh.billboardMode;
  15371. if (parsedMesh.visibility !== undefined) {
  15372. mesh.visibility = parsedMesh.visibility;
  15373. }
  15374. mesh.checkCollisions = parsedMesh.checkCollisions;
  15375. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15376. // freezeWorldMatrix
  15377. if (parsedMesh.freezeWorldMatrix) {
  15378. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15379. }
  15380. // Parent
  15381. if (parsedMesh.parentId) {
  15382. mesh._waitingParentId = parsedMesh.parentId;
  15383. }
  15384. // Actions
  15385. if (parsedMesh.actions !== undefined) {
  15386. mesh._waitingActions = parsedMesh.actions;
  15387. }
  15388. // Geometry
  15389. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15390. if (parsedMesh.delayLoadingFile) {
  15391. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15392. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15393. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15394. if (parsedMesh._binaryInfo) {
  15395. mesh._binaryInfo = parsedMesh._binaryInfo;
  15396. }
  15397. mesh._delayInfo = [];
  15398. if (parsedMesh.hasUVs) {
  15399. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15400. }
  15401. if (parsedMesh.hasUVs2) {
  15402. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15403. }
  15404. if (parsedMesh.hasUVs3) {
  15405. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15406. }
  15407. if (parsedMesh.hasUVs4) {
  15408. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15409. }
  15410. if (parsedMesh.hasUVs5) {
  15411. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15412. }
  15413. if (parsedMesh.hasUVs6) {
  15414. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15415. }
  15416. if (parsedMesh.hasColors) {
  15417. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15418. }
  15419. if (parsedMesh.hasMatricesIndices) {
  15420. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15421. }
  15422. if (parsedMesh.hasMatricesWeights) {
  15423. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15424. }
  15425. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15426. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15427. mesh._checkDelayState();
  15428. }
  15429. }
  15430. else {
  15431. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15432. }
  15433. // Material
  15434. if (parsedMesh.materialId) {
  15435. mesh.setMaterialByID(parsedMesh.materialId);
  15436. }
  15437. else {
  15438. mesh.material = null;
  15439. }
  15440. // Skeleton
  15441. if (parsedMesh.skeletonId > -1) {
  15442. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15443. if (parsedMesh.numBoneInfluencers) {
  15444. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15445. }
  15446. }
  15447. // Physics
  15448. if (parsedMesh.physicsImpostor) {
  15449. if (!scene.isPhysicsEnabled()) {
  15450. scene.enablePhysics();
  15451. }
  15452. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15453. }
  15454. // Animations
  15455. if (parsedMesh.animations) {
  15456. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15457. var parsedAnimation = parsedMesh.animations[animationIndex];
  15458. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15459. }
  15460. }
  15461. if (parsedMesh.autoAnimate) {
  15462. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15463. }
  15464. // Layer Mask
  15465. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15466. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15467. }
  15468. else {
  15469. mesh.layerMask = 0x0FFFFFFF;
  15470. }
  15471. // Instances
  15472. if (parsedMesh.instances) {
  15473. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15474. var parsedInstance = parsedMesh.instances[index];
  15475. var instance = mesh.createInstance(parsedInstance.name);
  15476. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15477. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15478. if (parsedInstance.rotationQuaternion) {
  15479. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15480. }
  15481. else if (parsedInstance.rotation) {
  15482. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15483. }
  15484. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15485. instance.checkCollisions = mesh.checkCollisions;
  15486. if (parsedMesh.animations) {
  15487. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15488. parsedAnimation = parsedMesh.animations[animationIndex];
  15489. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15490. }
  15491. }
  15492. }
  15493. }
  15494. return mesh;
  15495. };
  15496. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15497. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15498. pathArray: pathArray,
  15499. closeArray: closeArray,
  15500. closePath: closePath,
  15501. offset: offset,
  15502. updatable: updatable,
  15503. sideOrientation: sideOrientation,
  15504. instance: instance
  15505. }, scene);
  15506. };
  15507. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15508. var options = {
  15509. radius: radius,
  15510. tessellation: tessellation,
  15511. sideOrientation: sideOrientation,
  15512. updatable: updatable
  15513. };
  15514. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15515. };
  15516. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15517. var options = {
  15518. size: size,
  15519. sideOrientation: sideOrientation,
  15520. updatable: updatable
  15521. };
  15522. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15523. };
  15524. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15525. var options = {
  15526. segments: segments,
  15527. diameterX: diameter,
  15528. diameterY: diameter,
  15529. diameterZ: diameter,
  15530. sideOrientation: sideOrientation,
  15531. updatable: updatable
  15532. };
  15533. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15534. };
  15535. // Cylinder and cone
  15536. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15537. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15538. if (scene !== undefined) {
  15539. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15540. updatable = scene;
  15541. }
  15542. scene = subdivisions;
  15543. subdivisions = 1;
  15544. }
  15545. var options = {
  15546. height: height,
  15547. diameterTop: diameterTop,
  15548. diameterBottom: diameterBottom,
  15549. tessellation: tessellation,
  15550. subdivisions: subdivisions,
  15551. sideOrientation: sideOrientation,
  15552. updatable: updatable
  15553. };
  15554. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15555. };
  15556. // Torus (Code from SharpDX.org)
  15557. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15558. var options = {
  15559. diameter: diameter,
  15560. thickness: thickness,
  15561. tessellation: tessellation,
  15562. sideOrientation: sideOrientation,
  15563. updatable: updatable
  15564. };
  15565. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15566. };
  15567. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15568. var options = {
  15569. radius: radius,
  15570. tube: tube,
  15571. radialSegments: radialSegments,
  15572. tubularSegments: tubularSegments,
  15573. p: p,
  15574. q: q,
  15575. sideOrientation: sideOrientation,
  15576. updatable: updatable
  15577. };
  15578. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15579. };
  15580. // Lines
  15581. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15582. var options = {
  15583. points: points,
  15584. updatable: updatable,
  15585. instance: instance
  15586. };
  15587. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15588. };
  15589. // Dashed Lines
  15590. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15591. var options = {
  15592. points: points,
  15593. dashSize: dashSize,
  15594. gapSize: gapSize,
  15595. dashNb: dashNb,
  15596. updatable: updatable
  15597. };
  15598. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15599. };
  15600. // Extrusion
  15601. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15602. var options = {
  15603. shape: shape,
  15604. path: path,
  15605. scale: scale,
  15606. rotation: rotation,
  15607. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15608. sideOrientation: sideOrientation,
  15609. instance: instance,
  15610. updatable: updatable
  15611. };
  15612. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15613. };
  15614. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15615. var options = {
  15616. shape: shape,
  15617. path: path,
  15618. scaleFunction: scaleFunction,
  15619. rotationFunction: rotationFunction,
  15620. ribbonCloseArray: ribbonCloseArray,
  15621. ribbonClosePath: ribbonClosePath,
  15622. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15623. sideOrientation: sideOrientation,
  15624. instance: instance,
  15625. updatable: updatable
  15626. };
  15627. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15628. };
  15629. // Lathe
  15630. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15631. var options = {
  15632. shape: shape,
  15633. radius: radius,
  15634. tessellation: tessellation,
  15635. sideOrientation: sideOrientation,
  15636. updatable: updatable
  15637. };
  15638. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15639. };
  15640. // Plane & ground
  15641. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15642. var options = {
  15643. size: size,
  15644. width: size,
  15645. height: size,
  15646. sideOrientation: sideOrientation,
  15647. updatable: updatable
  15648. };
  15649. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15650. };
  15651. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15652. var options = {
  15653. width: width,
  15654. height: height,
  15655. subdivisions: subdivisions,
  15656. updatable: updatable
  15657. };
  15658. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15659. };
  15660. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15661. var options = {
  15662. xmin: xmin,
  15663. zmin: zmin,
  15664. xmax: xmax,
  15665. zmax: zmax,
  15666. subdivisions: subdivisions,
  15667. precision: precision,
  15668. updatable: updatable
  15669. };
  15670. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15671. };
  15672. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15673. var options = {
  15674. width: width,
  15675. height: height,
  15676. subdivisions: subdivisions,
  15677. minHeight: minHeight,
  15678. maxHeight: maxHeight,
  15679. updatable: updatable,
  15680. onReady: onReady
  15681. };
  15682. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15683. };
  15684. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15685. var options = {
  15686. path: path,
  15687. radius: radius,
  15688. tessellation: tessellation,
  15689. radiusFunction: radiusFunction,
  15690. arc: 1,
  15691. cap: cap,
  15692. updatable: updatable,
  15693. sideOrientation: sideOrientation,
  15694. instance: instance
  15695. };
  15696. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15697. };
  15698. Mesh.CreatePolyhedron = function (name, options, scene) {
  15699. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15700. };
  15701. Mesh.CreateIcoSphere = function (name, options, scene) {
  15702. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15703. };
  15704. // Decals
  15705. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15706. var options = {
  15707. position: position,
  15708. normal: normal,
  15709. size: size,
  15710. angle: angle
  15711. };
  15712. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15713. };
  15714. // Skeletons
  15715. /**
  15716. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15717. */
  15718. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15719. var source;
  15720. if (!this._sourcePositions) {
  15721. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15722. this._sourcePositions = new Float32Array(source);
  15723. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15724. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15725. }
  15726. }
  15727. return this._sourcePositions;
  15728. };
  15729. /**
  15730. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15731. */
  15732. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15733. var source;
  15734. if (!this._sourceNormals) {
  15735. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15736. this._sourceNormals = new Float32Array(source);
  15737. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15738. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15739. }
  15740. }
  15741. return this._sourceNormals;
  15742. };
  15743. /**
  15744. * Update the vertex buffers by applying transformation from the bones
  15745. * @param {skeleton} skeleton to apply
  15746. */
  15747. Mesh.prototype.applySkeleton = function (skeleton) {
  15748. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15749. return this;
  15750. }
  15751. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15752. return this;
  15753. }
  15754. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15755. return this;
  15756. }
  15757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15758. return this;
  15759. }
  15760. if (!this._sourcePositions) {
  15761. this.setPositionsForCPUSkinning();
  15762. }
  15763. if (!this._sourceNormals) {
  15764. this.setNormalsForCPUSkinning();
  15765. }
  15766. // positionsData checks for not being Float32Array will only pass at most once
  15767. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15768. if (!(positionsData instanceof Float32Array)) {
  15769. positionsData = new Float32Array(positionsData);
  15770. }
  15771. // normalsData checks for not being Float32Array will only pass at most once
  15772. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15773. if (!(normalsData instanceof Float32Array)) {
  15774. normalsData = new Float32Array(normalsData);
  15775. }
  15776. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15777. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15778. var needExtras = this.numBoneInfluencers > 4;
  15779. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15780. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15781. var skeletonMatrices = skeleton.getTransformMatrices();
  15782. var tempVector3 = BABYLON.Vector3.Zero();
  15783. var finalMatrix = new BABYLON.Matrix();
  15784. var tempMatrix = new BABYLON.Matrix();
  15785. var matWeightIdx = 0;
  15786. var inf;
  15787. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15788. var weight;
  15789. for (inf = 0; inf < 4; inf++) {
  15790. weight = matricesWeightsData[matWeightIdx + inf];
  15791. if (weight > 0) {
  15792. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15793. finalMatrix.addToSelf(tempMatrix);
  15794. }
  15795. else
  15796. break;
  15797. }
  15798. if (needExtras) {
  15799. for (inf = 0; inf < 4; inf++) {
  15800. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15801. if (weight > 0) {
  15802. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15803. finalMatrix.addToSelf(tempMatrix);
  15804. }
  15805. else
  15806. break;
  15807. }
  15808. }
  15809. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15810. tempVector3.toArray(positionsData, index);
  15811. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15812. tempVector3.toArray(normalsData, index);
  15813. finalMatrix.reset();
  15814. }
  15815. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15816. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15817. return this;
  15818. };
  15819. // Tools
  15820. Mesh.MinMax = function (meshes) {
  15821. var minVector = null;
  15822. var maxVector = null;
  15823. for (var i in meshes) {
  15824. var mesh = meshes[i];
  15825. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15826. if (!minVector) {
  15827. minVector = boundingBox.minimumWorld;
  15828. maxVector = boundingBox.maximumWorld;
  15829. continue;
  15830. }
  15831. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15832. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15833. }
  15834. return {
  15835. min: minVector,
  15836. max: maxVector
  15837. };
  15838. };
  15839. Mesh.Center = function (meshesOrMinMaxVector) {
  15840. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15841. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15842. };
  15843. /**
  15844. * Merge the array of meshes into a single mesh for performance reasons.
  15845. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15846. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15847. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15848. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15849. */
  15850. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15851. if (disposeSource === void 0) { disposeSource = true; }
  15852. var index;
  15853. if (!allow32BitsIndices) {
  15854. var totalVertices = 0;
  15855. // Counting vertices
  15856. for (index = 0; index < meshes.length; index++) {
  15857. if (meshes[index]) {
  15858. totalVertices += meshes[index].getTotalVertices();
  15859. if (totalVertices > 65536) {
  15860. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15861. return null;
  15862. }
  15863. }
  15864. }
  15865. }
  15866. // Merge
  15867. var vertexData;
  15868. var otherVertexData;
  15869. var source;
  15870. for (index = 0; index < meshes.length; index++) {
  15871. if (meshes[index]) {
  15872. meshes[index].computeWorldMatrix(true);
  15873. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15874. otherVertexData.transform(meshes[index].getWorldMatrix());
  15875. if (vertexData) {
  15876. vertexData.merge(otherVertexData);
  15877. }
  15878. else {
  15879. vertexData = otherVertexData;
  15880. source = meshes[index];
  15881. }
  15882. }
  15883. }
  15884. if (!meshSubclass) {
  15885. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15886. }
  15887. vertexData.applyToMesh(meshSubclass);
  15888. // Setting properties
  15889. meshSubclass.material = source.material;
  15890. meshSubclass.checkCollisions = source.checkCollisions;
  15891. // Cleaning
  15892. if (disposeSource) {
  15893. for (index = 0; index < meshes.length; index++) {
  15894. if (meshes[index]) {
  15895. meshes[index].dispose();
  15896. }
  15897. }
  15898. }
  15899. return meshSubclass;
  15900. };
  15901. // Consts
  15902. Mesh._FRONTSIDE = 0;
  15903. Mesh._BACKSIDE = 1;
  15904. Mesh._DOUBLESIDE = 2;
  15905. Mesh._DEFAULTSIDE = 0;
  15906. Mesh._NO_CAP = 0;
  15907. Mesh._CAP_START = 1;
  15908. Mesh._CAP_END = 2;
  15909. Mesh._CAP_ALL = 3;
  15910. return Mesh;
  15911. })(BABYLON.AbstractMesh);
  15912. BABYLON.Mesh = Mesh;
  15913. })(BABYLON || (BABYLON = {}));
  15914. var BABYLON;
  15915. (function (BABYLON) {
  15916. var SubMesh = (function () {
  15917. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15918. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15919. this.materialIndex = materialIndex;
  15920. this.verticesStart = verticesStart;
  15921. this.verticesCount = verticesCount;
  15922. this.indexStart = indexStart;
  15923. this.indexCount = indexCount;
  15924. this._renderId = 0;
  15925. this._mesh = mesh;
  15926. this._renderingMesh = renderingMesh || mesh;
  15927. mesh.subMeshes.push(this);
  15928. this._trianglePlanes = [];
  15929. this._id = mesh.subMeshes.length - 1;
  15930. if (createBoundingBox) {
  15931. this.refreshBoundingInfo();
  15932. mesh.computeWorldMatrix(true);
  15933. }
  15934. }
  15935. SubMesh.prototype.getBoundingInfo = function () {
  15936. return this._boundingInfo;
  15937. };
  15938. SubMesh.prototype.getMesh = function () {
  15939. return this._mesh;
  15940. };
  15941. SubMesh.prototype.getRenderingMesh = function () {
  15942. return this._renderingMesh;
  15943. };
  15944. SubMesh.prototype.getMaterial = function () {
  15945. var rootMaterial = this._renderingMesh.material;
  15946. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15947. var multiMaterial = rootMaterial;
  15948. return multiMaterial.getSubMaterial(this.materialIndex);
  15949. }
  15950. if (!rootMaterial) {
  15951. return this._mesh.getScene().defaultMaterial;
  15952. }
  15953. return rootMaterial;
  15954. };
  15955. // Methods
  15956. SubMesh.prototype.refreshBoundingInfo = function () {
  15957. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15958. if (!data) {
  15959. this._boundingInfo = this._mesh._boundingInfo;
  15960. return;
  15961. }
  15962. var indices = this._renderingMesh.getIndices();
  15963. var extend;
  15964. //is this the only submesh?
  15965. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15966. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15967. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15968. }
  15969. else {
  15970. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15971. }
  15972. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15973. };
  15974. SubMesh.prototype._checkCollision = function (collider) {
  15975. return this._boundingInfo._checkCollision(collider);
  15976. };
  15977. SubMesh.prototype.updateBoundingInfo = function (world) {
  15978. if (!this._boundingInfo) {
  15979. this.refreshBoundingInfo();
  15980. }
  15981. this._boundingInfo._update(world);
  15982. };
  15983. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15984. return this._boundingInfo.isInFrustum(frustumPlanes);
  15985. };
  15986. SubMesh.prototype.render = function (enableAlphaMode) {
  15987. this._renderingMesh.render(this, enableAlphaMode);
  15988. };
  15989. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15990. if (!this._linesIndexBuffer) {
  15991. var linesIndices = [];
  15992. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15993. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15994. }
  15995. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15996. this.linesIndexCount = linesIndices.length;
  15997. }
  15998. return this._linesIndexBuffer;
  15999. };
  16000. SubMesh.prototype.canIntersects = function (ray) {
  16001. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16002. };
  16003. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16004. var intersectInfo = null;
  16005. // Triangles test
  16006. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16007. var p0 = positions[indices[index]];
  16008. var p1 = positions[indices[index + 1]];
  16009. var p2 = positions[indices[index + 2]];
  16010. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16011. if (currentIntersectInfo) {
  16012. if (currentIntersectInfo.distance < 0) {
  16013. continue;
  16014. }
  16015. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16016. intersectInfo = currentIntersectInfo;
  16017. intersectInfo.faceId = index / 3;
  16018. if (fastCheck) {
  16019. break;
  16020. }
  16021. }
  16022. }
  16023. }
  16024. return intersectInfo;
  16025. };
  16026. // Clone
  16027. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16028. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16029. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16030. return result;
  16031. };
  16032. // Dispose
  16033. SubMesh.prototype.dispose = function () {
  16034. if (this._linesIndexBuffer) {
  16035. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16036. this._linesIndexBuffer = null;
  16037. }
  16038. // Remove from mesh
  16039. var index = this._mesh.subMeshes.indexOf(this);
  16040. this._mesh.subMeshes.splice(index, 1);
  16041. };
  16042. // Statics
  16043. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16044. var minVertexIndex = Number.MAX_VALUE;
  16045. var maxVertexIndex = -Number.MAX_VALUE;
  16046. renderingMesh = renderingMesh || mesh;
  16047. var indices = renderingMesh.getIndices();
  16048. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16049. var vertexIndex = indices[index];
  16050. if (vertexIndex < minVertexIndex)
  16051. minVertexIndex = vertexIndex;
  16052. if (vertexIndex > maxVertexIndex)
  16053. maxVertexIndex = vertexIndex;
  16054. }
  16055. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16056. };
  16057. return SubMesh;
  16058. })();
  16059. BABYLON.SubMesh = SubMesh;
  16060. })(BABYLON || (BABYLON = {}));
  16061. var BABYLON;
  16062. (function (BABYLON) {
  16063. var MeshBuilder = (function () {
  16064. function MeshBuilder() {
  16065. }
  16066. MeshBuilder.CreateBox = function (name, options, scene) {
  16067. var box = new BABYLON.Mesh(name, scene);
  16068. var vertexData = BABYLON.VertexData.CreateBox(options);
  16069. vertexData.applyToMesh(box, options.updatable);
  16070. return box;
  16071. };
  16072. MeshBuilder.CreateSphere = function (name, options, scene) {
  16073. var sphere = new BABYLON.Mesh(name, scene);
  16074. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16075. vertexData.applyToMesh(sphere, options.updatable);
  16076. return sphere;
  16077. };
  16078. MeshBuilder.CreateDisc = function (name, options, scene) {
  16079. var disc = new BABYLON.Mesh(name, scene);
  16080. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16081. vertexData.applyToMesh(disc, options.updatable);
  16082. return disc;
  16083. };
  16084. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16085. var sphere = new BABYLON.Mesh(name, scene);
  16086. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16087. vertexData.applyToMesh(sphere, options.updatable);
  16088. return sphere;
  16089. };
  16090. ;
  16091. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16092. var pathArray = options.pathArray;
  16093. var closeArray = options.closeArray;
  16094. var closePath = options.closePath;
  16095. var offset = options.offset;
  16096. var sideOrientation = options.sideOrientation;
  16097. var instance = options.instance;
  16098. var updatable = options.updatable;
  16099. if (instance) {
  16100. // positionFunction : ribbon case
  16101. // only pathArray and sideOrientation parameters are taken into account for positions update
  16102. var positionFunction = function (positions) {
  16103. var minlg = pathArray[0].length;
  16104. var i = 0;
  16105. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16106. for (var si = 1; si <= ns; si++) {
  16107. for (var p = 0; p < pathArray.length; p++) {
  16108. var path = pathArray[p];
  16109. var l = path.length;
  16110. minlg = (minlg < l) ? minlg : l;
  16111. var j = 0;
  16112. while (j < minlg) {
  16113. positions[i] = path[j].x;
  16114. positions[i + 1] = path[j].y;
  16115. positions[i + 2] = path[j].z;
  16116. j++;
  16117. i += 3;
  16118. }
  16119. if (instance._closePath) {
  16120. positions[i] = path[0].x;
  16121. positions[i + 1] = path[0].y;
  16122. positions[i + 2] = path[0].z;
  16123. i += 3;
  16124. }
  16125. }
  16126. }
  16127. };
  16128. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16129. positionFunction(positions);
  16130. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16131. if (!(instance.areNormalsFrozen)) {
  16132. var indices = instance.getIndices();
  16133. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16134. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16135. if (instance._closePath) {
  16136. var indexFirst = 0;
  16137. var indexLast = 0;
  16138. for (var p = 0; p < pathArray.length; p++) {
  16139. indexFirst = instance._idx[p] * 3;
  16140. if (p + 1 < pathArray.length) {
  16141. indexLast = (instance._idx[p + 1] - 1) * 3;
  16142. }
  16143. else {
  16144. indexLast = normals.length - 3;
  16145. }
  16146. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16147. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16148. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16149. normals[indexLast] = normals[indexFirst];
  16150. normals[indexLast + 1] = normals[indexFirst + 1];
  16151. normals[indexLast + 2] = normals[indexFirst + 2];
  16152. }
  16153. }
  16154. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16155. }
  16156. return instance;
  16157. }
  16158. else {
  16159. var ribbon = new BABYLON.Mesh(name, scene);
  16160. ribbon.sideOrientation = sideOrientation;
  16161. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16162. if (closePath) {
  16163. ribbon._idx = vertexData._idx;
  16164. }
  16165. ribbon._closePath = closePath;
  16166. ribbon._closeArray = closeArray;
  16167. vertexData.applyToMesh(ribbon, updatable);
  16168. return ribbon;
  16169. }
  16170. };
  16171. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16172. var cylinder = new BABYLON.Mesh(name, scene);
  16173. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16174. vertexData.applyToMesh(cylinder, options.updatable);
  16175. return cylinder;
  16176. };
  16177. MeshBuilder.CreateTorus = function (name, options, scene) {
  16178. var torus = new BABYLON.Mesh(name, scene);
  16179. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16180. vertexData.applyToMesh(torus, options.updatable);
  16181. return torus;
  16182. };
  16183. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16184. var torusKnot = new BABYLON.Mesh(name, scene);
  16185. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16186. vertexData.applyToMesh(torusKnot, options.updatable);
  16187. return torusKnot;
  16188. };
  16189. MeshBuilder.CreateLines = function (name, options, scene) {
  16190. var instance = options.instance;
  16191. var points = options.points;
  16192. if (instance) {
  16193. var positionFunction = function (positions) {
  16194. var i = 0;
  16195. for (var p = 0; p < points.length; p++) {
  16196. positions[i] = points[p].x;
  16197. positions[i + 1] = points[p].y;
  16198. positions[i + 2] = points[p].z;
  16199. i += 3;
  16200. }
  16201. };
  16202. instance.updateMeshPositions(positionFunction, false);
  16203. return instance;
  16204. }
  16205. // lines creation
  16206. var lines = new BABYLON.LinesMesh(name, scene);
  16207. var vertexData = BABYLON.VertexData.CreateLines(options);
  16208. vertexData.applyToMesh(lines, options.updatable);
  16209. return lines;
  16210. };
  16211. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16212. var points = options.points;
  16213. var instance = options.instance;
  16214. var gapSize = options.gapSize;
  16215. var dashNb = options.dashNb;
  16216. var dashSize = options.dashSize;
  16217. if (instance) {
  16218. var positionFunction = function (positions) {
  16219. var curvect = BABYLON.Vector3.Zero();
  16220. var nbSeg = positions.length / 6;
  16221. var lg = 0;
  16222. var nb = 0;
  16223. var shft = 0;
  16224. var dashshft = 0;
  16225. var curshft = 0;
  16226. var p = 0;
  16227. var i = 0;
  16228. var j = 0;
  16229. for (i = 0; i < points.length - 1; i++) {
  16230. points[i + 1].subtractToRef(points[i], curvect);
  16231. lg += curvect.length();
  16232. }
  16233. shft = lg / nbSeg;
  16234. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16235. for (i = 0; i < points.length - 1; i++) {
  16236. points[i + 1].subtractToRef(points[i], curvect);
  16237. nb = Math.floor(curvect.length() / shft);
  16238. curvect.normalize();
  16239. j = 0;
  16240. while (j < nb && p < positions.length) {
  16241. curshft = shft * j;
  16242. positions[p] = points[i].x + curshft * curvect.x;
  16243. positions[p + 1] = points[i].y + curshft * curvect.y;
  16244. positions[p + 2] = points[i].z + curshft * curvect.z;
  16245. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16246. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16247. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16248. p += 6;
  16249. j++;
  16250. }
  16251. }
  16252. while (p < positions.length) {
  16253. positions[p] = points[i].x;
  16254. positions[p + 1] = points[i].y;
  16255. positions[p + 2] = points[i].z;
  16256. p += 3;
  16257. }
  16258. };
  16259. instance.updateMeshPositions(positionFunction, false);
  16260. return instance;
  16261. }
  16262. // dashed lines creation
  16263. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16264. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16265. vertexData.applyToMesh(dashedLines, options.updatable);
  16266. dashedLines.dashSize = dashSize;
  16267. dashedLines.gapSize = gapSize;
  16268. return dashedLines;
  16269. };
  16270. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16271. var path = options.path;
  16272. var shape = options.shape;
  16273. var scale = options.scale || 1;
  16274. var rotation = options.rotation || 0;
  16275. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16276. var updatable = options.updatable;
  16277. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16278. var instance = options.instance;
  16279. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16280. };
  16281. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16282. var path = options.path;
  16283. var shape = options.shape;
  16284. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16285. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16286. var ribbonCloseArray = options.ribbonCloseArray || false;
  16287. var ribbonClosePath = options.ribbonClosePath || false;
  16288. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16289. var updatable = options.updatable;
  16290. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16291. var instance = options.instance;
  16292. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16293. };
  16294. MeshBuilder.CreateLathe = function (name, options, scene) {
  16295. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16296. var closed = (options.closed === undefined) ? true : options.closed;
  16297. var shape = options.shape;
  16298. var radius = options.radius || 1;
  16299. var tessellation = options.tessellation || 64;
  16300. var updatable = options.updatable;
  16301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16302. var pi2 = Math.PI * 2;
  16303. var shapeLathe = new Array();
  16304. // first rotatable point
  16305. var i = 0;
  16306. while (shape[i].x === 0) {
  16307. i++;
  16308. }
  16309. var pt = shape[i];
  16310. for (i = 0; i < shape.length; i++) {
  16311. shapeLathe.push(shape[i].subtract(pt));
  16312. }
  16313. // circle path
  16314. var step = pi2 / tessellation * arc;
  16315. var rotated;
  16316. var path = new Array();
  16317. ;
  16318. for (i = 0; i <= tessellation; i++) {
  16319. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16320. path.push(rotated);
  16321. }
  16322. if (closed) {
  16323. path.push(path[0]);
  16324. }
  16325. // extrusion
  16326. var scaleFunction = function () { return 1; };
  16327. var rotateFunction = function () { return 0; };
  16328. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16329. return lathe;
  16330. };
  16331. MeshBuilder.CreatePlane = function (name, options, scene) {
  16332. var plane = new BABYLON.Mesh(name, scene);
  16333. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16334. vertexData.applyToMesh(plane, options.updatable);
  16335. if (options.sourcePlane) {
  16336. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16337. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16338. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16339. plane.rotate(vectorProduct, product);
  16340. }
  16341. return plane;
  16342. };
  16343. MeshBuilder.CreateGround = function (name, options, scene) {
  16344. var ground = new BABYLON.GroundMesh(name, scene);
  16345. ground._setReady(false);
  16346. ground._subdivisions = options.subdivisions || 1;
  16347. var vertexData = BABYLON.VertexData.CreateGround(options);
  16348. vertexData.applyToMesh(ground, options.updatable);
  16349. ground._setReady(true);
  16350. return ground;
  16351. };
  16352. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16353. var tiledGround = new BABYLON.Mesh(name, scene);
  16354. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16355. vertexData.applyToMesh(tiledGround, options.updatable);
  16356. return tiledGround;
  16357. };
  16358. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16359. var width = options.width || 10;
  16360. var height = options.height || 10;
  16361. var subdivisions = options.subdivisions || 1;
  16362. var minHeight = options.minHeight;
  16363. var maxHeight = options.maxHeight || 10;
  16364. var updatable = options.updatable;
  16365. var onReady = options.onReady;
  16366. var ground = new BABYLON.GroundMesh(name, scene);
  16367. ground._subdivisions = subdivisions;
  16368. ground._setReady(false);
  16369. var onload = function (img) {
  16370. // Getting height map data
  16371. var canvas = document.createElement("canvas");
  16372. var context = canvas.getContext("2d");
  16373. var bufferWidth = img.width;
  16374. var bufferHeight = img.height;
  16375. canvas.width = bufferWidth;
  16376. canvas.height = bufferHeight;
  16377. context.drawImage(img, 0, 0);
  16378. // Create VertexData from map data
  16379. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16380. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16381. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16382. width: width, height: height,
  16383. subdivisions: subdivisions,
  16384. minHeight: minHeight, maxHeight: maxHeight,
  16385. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16386. });
  16387. vertexData.applyToMesh(ground, updatable);
  16388. ground._setReady(true);
  16389. //execute ready callback, if set
  16390. if (onReady) {
  16391. onReady(ground);
  16392. }
  16393. };
  16394. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16395. return ground;
  16396. };
  16397. MeshBuilder.CreateTube = function (name, options, scene) {
  16398. var path = options.path;
  16399. var radius = options.radius || 1;
  16400. var tessellation = options.tessellation || 64;
  16401. var radiusFunction = options.radiusFunction;
  16402. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16403. var updatable = options.updatable;
  16404. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16405. var instance = options.instance;
  16406. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16407. // tube geometry
  16408. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16409. var tangents = path3D.getTangents();
  16410. var normals = path3D.getNormals();
  16411. var distances = path3D.getDistances();
  16412. var pi2 = Math.PI * 2;
  16413. var step = pi2 / tessellation * arc;
  16414. var returnRadius = function () { return radius; };
  16415. var radiusFunctionFinal = radiusFunction || returnRadius;
  16416. var circlePath;
  16417. var rad;
  16418. var normal;
  16419. var rotated;
  16420. var rotationMatrix = BABYLON.Matrix.Zero();
  16421. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16422. for (var i = 0; i < path.length; i++) {
  16423. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16424. circlePath = Array(); // current circle array
  16425. normal = normals[i]; // current normal
  16426. for (var t = 0; t < tessellation; t++) {
  16427. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16428. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16429. circlePath.push(rotated);
  16430. }
  16431. circlePaths[index] = circlePath;
  16432. index++;
  16433. }
  16434. // cap
  16435. var capPath = function (nbPoints, pathIndex) {
  16436. var pointCap = Array();
  16437. for (var i = 0; i < nbPoints; i++) {
  16438. pointCap.push(path[pathIndex]);
  16439. }
  16440. return pointCap;
  16441. };
  16442. switch (cap) {
  16443. case BABYLON.Mesh.NO_CAP:
  16444. break;
  16445. case BABYLON.Mesh.CAP_START:
  16446. circlePaths[0] = capPath(tessellation, 0);
  16447. circlePaths[1] = circlePaths[2].slice(0);
  16448. break;
  16449. case BABYLON.Mesh.CAP_END:
  16450. circlePaths[index] = circlePaths[index - 1].slice(0);
  16451. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16452. break;
  16453. case BABYLON.Mesh.CAP_ALL:
  16454. circlePaths[0] = capPath(tessellation, 0);
  16455. circlePaths[1] = circlePaths[2].slice(0);
  16456. circlePaths[index] = circlePaths[index - 1].slice(0);
  16457. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16458. break;
  16459. default:
  16460. break;
  16461. }
  16462. return circlePaths;
  16463. };
  16464. var path3D;
  16465. var pathArray;
  16466. if (instance) {
  16467. var arc = options.arc || instance.arc;
  16468. path3D = (instance.path3D).update(path);
  16469. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16470. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16471. instance.path3D = path3D;
  16472. instance.pathArray = pathArray;
  16473. instance.arc = arc;
  16474. return instance;
  16475. }
  16476. // tube creation
  16477. path3D = new BABYLON.Path3D(path);
  16478. var newPathArray = new Array();
  16479. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16480. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16481. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16482. tube.pathArray = pathArray;
  16483. tube.path3D = path3D;
  16484. tube.tessellation = tessellation;
  16485. tube.cap = cap;
  16486. tube.arc = options.arc;
  16487. return tube;
  16488. };
  16489. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16490. var polyhedron = new BABYLON.Mesh(name, scene);
  16491. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16492. vertexData.applyToMesh(polyhedron, options.updatable);
  16493. return polyhedron;
  16494. };
  16495. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16496. var indices = sourceMesh.getIndices();
  16497. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16498. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16499. var position = options.position || BABYLON.Vector3.Zero();
  16500. var normal = options.normal || BABYLON.Vector3.Up();
  16501. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16502. var angle = options.angle || 0;
  16503. // Getting correct rotation
  16504. if (!normal) {
  16505. var target = new BABYLON.Vector3(0, 0, 1);
  16506. var camera = sourceMesh.getScene().activeCamera;
  16507. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16508. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16509. }
  16510. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16511. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16512. var pitch = Math.atan2(normal.y, len);
  16513. // Matrix
  16514. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16515. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16516. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16517. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16518. var vertexData = new BABYLON.VertexData();
  16519. vertexData.indices = [];
  16520. vertexData.positions = [];
  16521. vertexData.normals = [];
  16522. vertexData.uvs = [];
  16523. var currentVertexDataIndex = 0;
  16524. var extractDecalVector3 = function (indexId) {
  16525. var vertexId = indices[indexId];
  16526. var result = new BABYLON.PositionNormalVertex();
  16527. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16528. // Send vector to decal local world
  16529. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16530. // Get normal
  16531. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16532. return result;
  16533. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16534. var clip = function (vertices, axis) {
  16535. if (vertices.length === 0) {
  16536. return vertices;
  16537. }
  16538. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16539. var clipVertices = function (v0, v1) {
  16540. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16541. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16542. };
  16543. var result = new Array();
  16544. for (var index = 0; index < vertices.length; index += 3) {
  16545. var v1Out;
  16546. var v2Out;
  16547. var v3Out;
  16548. var total = 0;
  16549. var nV1, nV2, nV3, nV4;
  16550. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16551. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16552. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16553. v1Out = d1 > 0;
  16554. v2Out = d2 > 0;
  16555. v3Out = d3 > 0;
  16556. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16557. switch (total) {
  16558. case 0:
  16559. result.push(vertices[index]);
  16560. result.push(vertices[index + 1]);
  16561. result.push(vertices[index + 2]);
  16562. break;
  16563. case 1:
  16564. if (v1Out) {
  16565. nV1 = vertices[index + 1];
  16566. nV2 = vertices[index + 2];
  16567. nV3 = clipVertices(vertices[index], nV1);
  16568. nV4 = clipVertices(vertices[index], nV2);
  16569. }
  16570. if (v2Out) {
  16571. nV1 = vertices[index];
  16572. nV2 = vertices[index + 2];
  16573. nV3 = clipVertices(vertices[index + 1], nV1);
  16574. nV4 = clipVertices(vertices[index + 1], nV2);
  16575. result.push(nV3);
  16576. result.push(nV2.clone());
  16577. result.push(nV1.clone());
  16578. result.push(nV2.clone());
  16579. result.push(nV3.clone());
  16580. result.push(nV4);
  16581. break;
  16582. }
  16583. if (v3Out) {
  16584. nV1 = vertices[index];
  16585. nV2 = vertices[index + 1];
  16586. nV3 = clipVertices(vertices[index + 2], nV1);
  16587. nV4 = clipVertices(vertices[index + 2], nV2);
  16588. }
  16589. result.push(nV1.clone());
  16590. result.push(nV2.clone());
  16591. result.push(nV3);
  16592. result.push(nV4);
  16593. result.push(nV3.clone());
  16594. result.push(nV2.clone());
  16595. break;
  16596. case 2:
  16597. if (!v1Out) {
  16598. nV1 = vertices[index].clone();
  16599. nV2 = clipVertices(nV1, vertices[index + 1]);
  16600. nV3 = clipVertices(nV1, vertices[index + 2]);
  16601. result.push(nV1);
  16602. result.push(nV2);
  16603. result.push(nV3);
  16604. }
  16605. if (!v2Out) {
  16606. nV1 = vertices[index + 1].clone();
  16607. nV2 = clipVertices(nV1, vertices[index + 2]);
  16608. nV3 = clipVertices(nV1, vertices[index]);
  16609. result.push(nV1);
  16610. result.push(nV2);
  16611. result.push(nV3);
  16612. }
  16613. if (!v3Out) {
  16614. nV1 = vertices[index + 2].clone();
  16615. nV2 = clipVertices(nV1, vertices[index]);
  16616. nV3 = clipVertices(nV1, vertices[index + 1]);
  16617. result.push(nV1);
  16618. result.push(nV2);
  16619. result.push(nV3);
  16620. }
  16621. break;
  16622. case 3:
  16623. break;
  16624. }
  16625. }
  16626. return result;
  16627. };
  16628. for (var index = 0; index < indices.length; index += 3) {
  16629. var faceVertices = new Array();
  16630. faceVertices.push(extractDecalVector3(index));
  16631. faceVertices.push(extractDecalVector3(index + 1));
  16632. faceVertices.push(extractDecalVector3(index + 2));
  16633. // Clip
  16634. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16635. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16636. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16637. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16638. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16639. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16640. if (faceVertices.length === 0) {
  16641. continue;
  16642. }
  16643. // Add UVs and get back to world
  16644. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16645. var vertex = faceVertices[vIndex];
  16646. //TODO check for Int32Array
  16647. vertexData.indices.push(currentVertexDataIndex);
  16648. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16649. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16650. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16651. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16652. currentVertexDataIndex++;
  16653. }
  16654. }
  16655. // Return mesh
  16656. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16657. vertexData.applyToMesh(decal);
  16658. decal.position = position.clone();
  16659. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16660. return decal;
  16661. };
  16662. // Privates
  16663. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16664. // extrusion geometry
  16665. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16666. var tangents = path3D.getTangents();
  16667. var normals = path3D.getNormals();
  16668. var binormals = path3D.getBinormals();
  16669. var distances = path3D.getDistances();
  16670. var angle = 0;
  16671. var returnScale = function () { return scale; };
  16672. var returnRotation = function () { return rotation; };
  16673. var rotate = custom ? rotateFunction : returnRotation;
  16674. var scl = custom ? scaleFunction : returnScale;
  16675. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16676. var rotationMatrix = BABYLON.Matrix.Zero();
  16677. for (var i = 0; i < curve.length; i++) {
  16678. var shapePath = new Array();
  16679. var angleStep = rotate(i, distances[i]);
  16680. var scaleRatio = scl(i, distances[i]);
  16681. for (var p = 0; p < shape.length; p++) {
  16682. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16683. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16684. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16685. shapePath.push(rotated);
  16686. }
  16687. shapePaths[index] = shapePath;
  16688. angle += angleStep;
  16689. index++;
  16690. }
  16691. // cap
  16692. var capPath = function (shapePath) {
  16693. var pointCap = Array();
  16694. var barycenter = BABYLON.Vector3.Zero();
  16695. var i;
  16696. for (i = 0; i < shapePath.length; i++) {
  16697. barycenter.addInPlace(shapePath[i]);
  16698. }
  16699. barycenter.scaleInPlace(1 / shapePath.length);
  16700. for (i = 0; i < shapePath.length; i++) {
  16701. pointCap.push(barycenter);
  16702. }
  16703. return pointCap;
  16704. };
  16705. switch (cap) {
  16706. case BABYLON.Mesh.NO_CAP:
  16707. break;
  16708. case BABYLON.Mesh.CAP_START:
  16709. shapePaths[0] = capPath(shapePaths[2]);
  16710. shapePaths[1] = shapePaths[2].slice(0);
  16711. break;
  16712. case BABYLON.Mesh.CAP_END:
  16713. shapePaths[index] = shapePaths[index - 1];
  16714. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16715. break;
  16716. case BABYLON.Mesh.CAP_ALL:
  16717. shapePaths[0] = capPath(shapePaths[2]);
  16718. shapePaths[1] = shapePaths[2].slice(0);
  16719. shapePaths[index] = shapePaths[index - 1];
  16720. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16721. break;
  16722. default:
  16723. break;
  16724. }
  16725. return shapePaths;
  16726. };
  16727. var path3D;
  16728. var pathArray;
  16729. if (instance) {
  16730. path3D = (instance.path3D).update(curve);
  16731. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16732. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16733. return instance;
  16734. }
  16735. // extruded shape creation
  16736. path3D = new BABYLON.Path3D(curve);
  16737. var newShapePaths = new Array();
  16738. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16739. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16740. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16741. extrudedGeneric.pathArray = pathArray;
  16742. extrudedGeneric.path3D = path3D;
  16743. extrudedGeneric.cap = cap;
  16744. return extrudedGeneric;
  16745. };
  16746. return MeshBuilder;
  16747. })();
  16748. BABYLON.MeshBuilder = MeshBuilder;
  16749. })(BABYLON || (BABYLON = {}));
  16750. var BABYLON;
  16751. (function (BABYLON) {
  16752. var BaseTexture = (function () {
  16753. function BaseTexture(scene) {
  16754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16755. this.hasAlpha = false;
  16756. this.getAlphaFromRGB = false;
  16757. this.level = 1;
  16758. this.isCube = false;
  16759. this.isRenderTarget = false;
  16760. this.animations = new Array();
  16761. this.coordinatesIndex = 0;
  16762. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16763. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16764. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16765. this.anisotropicFilteringLevel = 4;
  16766. this._scene = scene;
  16767. this._scene.textures.push(this);
  16768. }
  16769. BaseTexture.prototype.getScene = function () {
  16770. return this._scene;
  16771. };
  16772. BaseTexture.prototype.getTextureMatrix = function () {
  16773. return null;
  16774. };
  16775. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16776. return null;
  16777. };
  16778. BaseTexture.prototype.getInternalTexture = function () {
  16779. return this._texture;
  16780. };
  16781. BaseTexture.prototype.isReady = function () {
  16782. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16783. return true;
  16784. }
  16785. if (this._texture) {
  16786. return this._texture.isReady;
  16787. }
  16788. return false;
  16789. };
  16790. BaseTexture.prototype.getSize = function () {
  16791. if (this._texture._width) {
  16792. return { width: this._texture._width, height: this._texture._height };
  16793. }
  16794. if (this._texture._size) {
  16795. return { width: this._texture._size, height: this._texture._size };
  16796. }
  16797. return { width: 0, height: 0 };
  16798. };
  16799. BaseTexture.prototype.getBaseSize = function () {
  16800. if (!this.isReady())
  16801. return { width: 0, height: 0 };
  16802. if (this._texture._size) {
  16803. return { width: this._texture._size, height: this._texture._size };
  16804. }
  16805. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16806. };
  16807. BaseTexture.prototype.scale = function (ratio) {
  16808. };
  16809. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16810. get: function () {
  16811. return false;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16817. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16818. for (var index = 0; index < texturesCache.length; index++) {
  16819. var texturesCacheEntry = texturesCache[index];
  16820. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16821. texturesCache.splice(index, 1);
  16822. return;
  16823. }
  16824. }
  16825. };
  16826. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16827. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16828. for (var index = 0; index < texturesCache.length; index++) {
  16829. var texturesCacheEntry = texturesCache[index];
  16830. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16831. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16832. texturesCacheEntry.references++;
  16833. return texturesCacheEntry;
  16834. }
  16835. }
  16836. }
  16837. return null;
  16838. };
  16839. BaseTexture.prototype.delayLoad = function () {
  16840. };
  16841. BaseTexture.prototype.clone = function () {
  16842. return null;
  16843. };
  16844. BaseTexture.prototype.releaseInternalTexture = function () {
  16845. if (this._texture) {
  16846. this._scene.getEngine().releaseInternalTexture(this._texture);
  16847. delete this._texture;
  16848. }
  16849. };
  16850. BaseTexture.prototype.dispose = function () {
  16851. // Animations
  16852. this.getScene().stopAnimation(this);
  16853. // Remove from scene
  16854. var index = this._scene.textures.indexOf(this);
  16855. if (index >= 0) {
  16856. this._scene.textures.splice(index, 1);
  16857. }
  16858. if (this._texture === undefined) {
  16859. return;
  16860. }
  16861. // Release
  16862. this.releaseInternalTexture();
  16863. // Callback
  16864. if (this.onDispose) {
  16865. this.onDispose();
  16866. }
  16867. };
  16868. BaseTexture.prototype.serialize = function () {
  16869. var serializationObject = {};
  16870. if (!this.name) {
  16871. return null;
  16872. }
  16873. serializationObject.name = this.name;
  16874. serializationObject.hasAlpha = this.hasAlpha;
  16875. serializationObject.level = this.level;
  16876. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16877. serializationObject.coordinatesMode = this.coordinatesMode;
  16878. serializationObject.wrapU = this.wrapU;
  16879. serializationObject.wrapV = this.wrapV;
  16880. // Animations
  16881. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16882. return serializationObject;
  16883. };
  16884. return BaseTexture;
  16885. })();
  16886. BABYLON.BaseTexture = BaseTexture;
  16887. })(BABYLON || (BABYLON = {}));
  16888. var BABYLON;
  16889. (function (BABYLON) {
  16890. var Texture = (function (_super) {
  16891. __extends(Texture, _super);
  16892. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16893. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16894. if (onLoad === void 0) { onLoad = null; }
  16895. if (onError === void 0) { onError = null; }
  16896. if (buffer === void 0) { buffer = null; }
  16897. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16898. _super.call(this, scene);
  16899. this.uOffset = 0;
  16900. this.vOffset = 0;
  16901. this.uScale = 1.0;
  16902. this.vScale = 1.0;
  16903. this.uAng = 0;
  16904. this.vAng = 0;
  16905. this.wAng = 0;
  16906. this.name = url;
  16907. this.url = url;
  16908. this._noMipmap = noMipmap;
  16909. this._invertY = invertY;
  16910. this._samplingMode = samplingMode;
  16911. this._buffer = buffer;
  16912. this._deleteBuffer = deleteBuffer;
  16913. if (!url) {
  16914. return;
  16915. }
  16916. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16917. if (!this._texture) {
  16918. if (!scene.useDelayedTextureLoading) {
  16919. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16920. if (deleteBuffer) {
  16921. delete this._buffer;
  16922. }
  16923. }
  16924. else {
  16925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16926. }
  16927. }
  16928. else {
  16929. BABYLON.Tools.SetImmediate(function () {
  16930. if (onLoad) {
  16931. onLoad();
  16932. }
  16933. });
  16934. }
  16935. }
  16936. Texture.prototype.delayLoad = function () {
  16937. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16938. return;
  16939. }
  16940. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16941. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16942. if (!this._texture) {
  16943. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16944. if (this._deleteBuffer) {
  16945. delete this._buffer;
  16946. }
  16947. }
  16948. };
  16949. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16950. if (!this._texture) {
  16951. return;
  16952. }
  16953. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16954. };
  16955. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16956. x *= this.uScale;
  16957. y *= this.vScale;
  16958. x -= 0.5 * this.uScale;
  16959. y -= 0.5 * this.vScale;
  16960. z -= 0.5;
  16961. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16962. t.x += 0.5 * this.uScale + this.uOffset;
  16963. t.y += 0.5 * this.vScale + this.vOffset;
  16964. t.z += 0.5;
  16965. };
  16966. Texture.prototype.getTextureMatrix = function () {
  16967. if (this.uOffset === this._cachedUOffset &&
  16968. this.vOffset === this._cachedVOffset &&
  16969. this.uScale === this._cachedUScale &&
  16970. this.vScale === this._cachedVScale &&
  16971. this.uAng === this._cachedUAng &&
  16972. this.vAng === this._cachedVAng &&
  16973. this.wAng === this._cachedWAng) {
  16974. return this._cachedTextureMatrix;
  16975. }
  16976. this._cachedUOffset = this.uOffset;
  16977. this._cachedVOffset = this.vOffset;
  16978. this._cachedUScale = this.uScale;
  16979. this._cachedVScale = this.vScale;
  16980. this._cachedUAng = this.uAng;
  16981. this._cachedVAng = this.vAng;
  16982. this._cachedWAng = this.wAng;
  16983. if (!this._cachedTextureMatrix) {
  16984. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16985. this._rowGenerationMatrix = new BABYLON.Matrix();
  16986. this._t0 = BABYLON.Vector3.Zero();
  16987. this._t1 = BABYLON.Vector3.Zero();
  16988. this._t2 = BABYLON.Vector3.Zero();
  16989. }
  16990. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16991. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16992. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16993. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16994. this._t1.subtractInPlace(this._t0);
  16995. this._t2.subtractInPlace(this._t0);
  16996. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16997. this._cachedTextureMatrix.m[0] = this._t1.x;
  16998. this._cachedTextureMatrix.m[1] = this._t1.y;
  16999. this._cachedTextureMatrix.m[2] = this._t1.z;
  17000. this._cachedTextureMatrix.m[4] = this._t2.x;
  17001. this._cachedTextureMatrix.m[5] = this._t2.y;
  17002. this._cachedTextureMatrix.m[6] = this._t2.z;
  17003. this._cachedTextureMatrix.m[8] = this._t0.x;
  17004. this._cachedTextureMatrix.m[9] = this._t0.y;
  17005. this._cachedTextureMatrix.m[10] = this._t0.z;
  17006. return this._cachedTextureMatrix;
  17007. };
  17008. Texture.prototype.getReflectionTextureMatrix = function () {
  17009. if (this.uOffset === this._cachedUOffset &&
  17010. this.vOffset === this._cachedVOffset &&
  17011. this.uScale === this._cachedUScale &&
  17012. this.vScale === this._cachedVScale &&
  17013. this.coordinatesMode === this._cachedCoordinatesMode) {
  17014. return this._cachedTextureMatrix;
  17015. }
  17016. if (!this._cachedTextureMatrix) {
  17017. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17018. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17019. }
  17020. this._cachedCoordinatesMode = this.coordinatesMode;
  17021. switch (this.coordinatesMode) {
  17022. case Texture.PLANAR_MODE:
  17023. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17024. this._cachedTextureMatrix[0] = this.uScale;
  17025. this._cachedTextureMatrix[5] = this.vScale;
  17026. this._cachedTextureMatrix[12] = this.uOffset;
  17027. this._cachedTextureMatrix[13] = this.vOffset;
  17028. break;
  17029. case Texture.PROJECTION_MODE:
  17030. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17031. this._projectionModeMatrix.m[0] = 0.5;
  17032. this._projectionModeMatrix.m[5] = -0.5;
  17033. this._projectionModeMatrix.m[10] = 0.0;
  17034. this._projectionModeMatrix.m[12] = 0.5;
  17035. this._projectionModeMatrix.m[13] = 0.5;
  17036. this._projectionModeMatrix.m[14] = 1.0;
  17037. this._projectionModeMatrix.m[15] = 1.0;
  17038. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17039. break;
  17040. default:
  17041. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17042. break;
  17043. }
  17044. return this._cachedTextureMatrix;
  17045. };
  17046. Texture.prototype.clone = function () {
  17047. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17048. // Base texture
  17049. newTexture.hasAlpha = this.hasAlpha;
  17050. newTexture.level = this.level;
  17051. newTexture.wrapU = this.wrapU;
  17052. newTexture.wrapV = this.wrapV;
  17053. newTexture.coordinatesIndex = this.coordinatesIndex;
  17054. newTexture.coordinatesMode = this.coordinatesMode;
  17055. // Texture
  17056. newTexture.uOffset = this.uOffset;
  17057. newTexture.vOffset = this.vOffset;
  17058. newTexture.uScale = this.uScale;
  17059. newTexture.vScale = this.vScale;
  17060. newTexture.uAng = this.uAng;
  17061. newTexture.vAng = this.vAng;
  17062. newTexture.wAng = this.wAng;
  17063. return newTexture;
  17064. };
  17065. Texture.prototype.serialize = function () {
  17066. if (!this.name) {
  17067. return null;
  17068. }
  17069. var serializationObject = _super.prototype.serialize.call(this);
  17070. serializationObject.uOffset = this.uOffset;
  17071. serializationObject.vOffset = this.vOffset;
  17072. serializationObject.uScale = this.uScale;
  17073. serializationObject.vScale = this.vScale;
  17074. serializationObject.uAng = this.uAng;
  17075. serializationObject.vAng = this.vAng;
  17076. serializationObject.wAng = this.wAng;
  17077. return serializationObject;
  17078. };
  17079. // Statics
  17080. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17081. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17082. if (onLoad === void 0) { onLoad = null; }
  17083. if (onError === void 0) { onError = null; }
  17084. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17085. };
  17086. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17087. if (parsedTexture.isCube) {
  17088. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17089. }
  17090. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17091. return null;
  17092. }
  17093. var texture;
  17094. if (parsedTexture.mirrorPlane) {
  17095. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17096. texture._waitingRenderList = parsedTexture.renderList;
  17097. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17098. }
  17099. else if (parsedTexture.isRenderTarget) {
  17100. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17101. texture._waitingRenderList = parsedTexture.renderList;
  17102. }
  17103. else {
  17104. if (parsedTexture.base64String) {
  17105. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17106. }
  17107. else {
  17108. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17109. }
  17110. }
  17111. texture.name = parsedTexture.name;
  17112. texture.hasAlpha = parsedTexture.hasAlpha;
  17113. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17114. texture.level = parsedTexture.level;
  17115. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17116. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17117. texture.uOffset = parsedTexture.uOffset;
  17118. texture.vOffset = parsedTexture.vOffset;
  17119. texture.uScale = parsedTexture.uScale;
  17120. texture.vScale = parsedTexture.vScale;
  17121. texture.uAng = parsedTexture.uAng;
  17122. texture.vAng = parsedTexture.vAng;
  17123. texture.wAng = parsedTexture.wAng;
  17124. texture.wrapU = parsedTexture.wrapU;
  17125. texture.wrapV = parsedTexture.wrapV;
  17126. // Animations
  17127. if (parsedTexture.animations) {
  17128. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17129. var parsedAnimation = parsedTexture.animations[animationIndex];
  17130. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17131. }
  17132. }
  17133. return texture;
  17134. };
  17135. // Constants
  17136. Texture.NEAREST_SAMPLINGMODE = 1;
  17137. Texture.BILINEAR_SAMPLINGMODE = 2;
  17138. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17139. Texture.EXPLICIT_MODE = 0;
  17140. Texture.SPHERICAL_MODE = 1;
  17141. Texture.PLANAR_MODE = 2;
  17142. Texture.CUBIC_MODE = 3;
  17143. Texture.PROJECTION_MODE = 4;
  17144. Texture.SKYBOX_MODE = 5;
  17145. Texture.INVCUBIC_MODE = 6;
  17146. Texture.EQUIRECTANGULAR_MODE = 7;
  17147. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17148. Texture.CLAMP_ADDRESSMODE = 0;
  17149. Texture.WRAP_ADDRESSMODE = 1;
  17150. Texture.MIRROR_ADDRESSMODE = 2;
  17151. return Texture;
  17152. })(BABYLON.BaseTexture);
  17153. BABYLON.Texture = Texture;
  17154. })(BABYLON || (BABYLON = {}));
  17155. var BABYLON;
  17156. (function (BABYLON) {
  17157. var CubeTexture = (function (_super) {
  17158. __extends(CubeTexture, _super);
  17159. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17160. _super.call(this, scene);
  17161. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17162. this.name = rootUrl;
  17163. this.url = rootUrl;
  17164. this._noMipmap = noMipmap;
  17165. this.hasAlpha = false;
  17166. if (!rootUrl) {
  17167. return;
  17168. }
  17169. this._texture = this._getFromCache(rootUrl, noMipmap);
  17170. if (!extensions) {
  17171. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17172. }
  17173. this._extensions = extensions;
  17174. if (!this._texture) {
  17175. if (!scene.useDelayedTextureLoading) {
  17176. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17177. }
  17178. else {
  17179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17180. }
  17181. }
  17182. this.isCube = true;
  17183. this._textureMatrix = BABYLON.Matrix.Identity();
  17184. }
  17185. CubeTexture.prototype.clone = function () {
  17186. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17187. // Base texture
  17188. newTexture.level = this.level;
  17189. newTexture.wrapU = this.wrapU;
  17190. newTexture.wrapV = this.wrapV;
  17191. newTexture.coordinatesIndex = this.coordinatesIndex;
  17192. newTexture.coordinatesMode = this.coordinatesMode;
  17193. return newTexture;
  17194. };
  17195. // Methods
  17196. CubeTexture.prototype.delayLoad = function () {
  17197. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17198. return;
  17199. }
  17200. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17201. this._texture = this._getFromCache(this.url, this._noMipmap);
  17202. if (!this._texture) {
  17203. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17204. }
  17205. };
  17206. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17207. return this._textureMatrix;
  17208. };
  17209. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17210. var texture = null;
  17211. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17212. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17213. texture.name = parsedTexture.name;
  17214. texture.hasAlpha = parsedTexture.hasAlpha;
  17215. texture.level = parsedTexture.level;
  17216. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17217. }
  17218. return texture;
  17219. };
  17220. CubeTexture.prototype.serialize = function () {
  17221. if (!this.name) {
  17222. return null;
  17223. }
  17224. var serializationObject = {};
  17225. serializationObject.name = this.name;
  17226. serializationObject.hasAlpha = this.hasAlpha;
  17227. serializationObject.isCube = true;
  17228. serializationObject.level = this.level;
  17229. serializationObject.coordinatesMode = this.coordinatesMode;
  17230. return serializationObject;
  17231. };
  17232. return CubeTexture;
  17233. })(BABYLON.BaseTexture);
  17234. BABYLON.CubeTexture = CubeTexture;
  17235. })(BABYLON || (BABYLON = {}));
  17236. var BABYLON;
  17237. (function (BABYLON) {
  17238. var RenderTargetTexture = (function (_super) {
  17239. __extends(RenderTargetTexture, _super);
  17240. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17241. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17242. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17243. if (isCube === void 0) { isCube = false; }
  17244. _super.call(this, null, scene, !generateMipMaps);
  17245. this.isCube = isCube;
  17246. this.renderList = new Array();
  17247. this.renderParticles = true;
  17248. this.renderSprites = false;
  17249. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17250. this._currentRefreshId = -1;
  17251. this._refreshRate = 1;
  17252. this.name = name;
  17253. this.isRenderTarget = true;
  17254. this._size = size;
  17255. this._generateMipMaps = generateMipMaps;
  17256. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17257. if (isCube) {
  17258. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17259. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17260. this._textureMatrix = BABYLON.Matrix.Identity();
  17261. }
  17262. else {
  17263. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17264. }
  17265. // Rendering groups
  17266. this._renderingManager = new BABYLON.RenderingManager(scene);
  17267. }
  17268. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17269. get: function () {
  17270. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17276. get: function () {
  17277. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17278. },
  17279. enumerable: true,
  17280. configurable: true
  17281. });
  17282. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17283. get: function () {
  17284. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17285. },
  17286. enumerable: true,
  17287. configurable: true
  17288. });
  17289. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17290. this._currentRefreshId = -1;
  17291. };
  17292. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17293. get: function () {
  17294. return this._refreshRate;
  17295. },
  17296. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17297. set: function (value) {
  17298. this._refreshRate = value;
  17299. this.resetRefreshCounter();
  17300. },
  17301. enumerable: true,
  17302. configurable: true
  17303. });
  17304. RenderTargetTexture.prototype._shouldRender = function () {
  17305. if (this._currentRefreshId === -1) {
  17306. this._currentRefreshId = 1;
  17307. return true;
  17308. }
  17309. if (this.refreshRate === this._currentRefreshId) {
  17310. this._currentRefreshId = 1;
  17311. return true;
  17312. }
  17313. this._currentRefreshId++;
  17314. return false;
  17315. };
  17316. RenderTargetTexture.prototype.isReady = function () {
  17317. if (!this.getScene().renderTargetsEnabled) {
  17318. return false;
  17319. }
  17320. return _super.prototype.isReady.call(this);
  17321. };
  17322. RenderTargetTexture.prototype.getRenderSize = function () {
  17323. return this._size;
  17324. };
  17325. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17326. get: function () {
  17327. return true;
  17328. },
  17329. enumerable: true,
  17330. configurable: true
  17331. });
  17332. RenderTargetTexture.prototype.scale = function (ratio) {
  17333. var newSize = this._size * ratio;
  17334. this.resize(newSize, this._generateMipMaps);
  17335. };
  17336. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17337. if (this.isCube) {
  17338. return this._textureMatrix;
  17339. }
  17340. return _super.prototype.getReflectionTextureMatrix.call(this);
  17341. };
  17342. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17343. this.releaseInternalTexture();
  17344. if (this.isCube) {
  17345. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17346. }
  17347. else {
  17348. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17349. }
  17350. };
  17351. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17352. var scene = this.getScene();
  17353. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17354. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17355. }
  17356. if (this._waitingRenderList) {
  17357. this.renderList = [];
  17358. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17359. var id = this._waitingRenderList[index];
  17360. this.renderList.push(scene.getMeshByID(id));
  17361. }
  17362. delete this._waitingRenderList;
  17363. }
  17364. if (this.renderList && this.renderList.length === 0) {
  17365. return;
  17366. }
  17367. // Prepare renderingManager
  17368. this._renderingManager.reset();
  17369. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17370. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17371. var mesh = currentRenderList[meshIndex];
  17372. if (mesh) {
  17373. if (!mesh.isReady()) {
  17374. // Reset _currentRefreshId
  17375. this.resetRefreshCounter();
  17376. continue;
  17377. }
  17378. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17379. mesh._activate(scene.getRenderId());
  17380. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17381. var subMesh = mesh.subMeshes[subIndex];
  17382. scene._activeIndices += subMesh.indexCount;
  17383. this._renderingManager.dispatch(subMesh);
  17384. }
  17385. }
  17386. }
  17387. }
  17388. if (this.isCube) {
  17389. for (var face = 0; face < 6; face++) {
  17390. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17391. }
  17392. }
  17393. else {
  17394. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17395. }
  17396. if (this.onAfterUnbind) {
  17397. this.onAfterUnbind();
  17398. }
  17399. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17400. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17401. }
  17402. scene.resetCachedMaterial();
  17403. };
  17404. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17405. var scene = this.getScene();
  17406. var engine = scene.getEngine();
  17407. // Bind
  17408. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17409. if (this.isCube) {
  17410. engine.bindFramebuffer(this._texture, faceIndex);
  17411. }
  17412. else {
  17413. engine.bindFramebuffer(this._texture);
  17414. }
  17415. }
  17416. if (this.onBeforeRender) {
  17417. this.onBeforeRender(faceIndex);
  17418. }
  17419. // Clear
  17420. if (this.onClear) {
  17421. this.onClear(engine);
  17422. }
  17423. else {
  17424. engine.clear(scene.clearColor, true, true);
  17425. }
  17426. if (!this._doNotChangeAspectRatio) {
  17427. scene.updateTransformMatrix(true);
  17428. }
  17429. // Render
  17430. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17431. if (useCameraPostProcess) {
  17432. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17433. }
  17434. if (!this._doNotChangeAspectRatio) {
  17435. scene.updateTransformMatrix(true);
  17436. }
  17437. if (this.onAfterRender) {
  17438. this.onAfterRender(faceIndex);
  17439. }
  17440. // Dump ?
  17441. if (dumpForDebug) {
  17442. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17443. }
  17444. // Unbind
  17445. if (!this.isCube || faceIndex === 5) {
  17446. if (this.isCube) {
  17447. if (faceIndex === 5) {
  17448. engine.generateMipMapsForCubemap(this._texture);
  17449. }
  17450. }
  17451. engine.unBindFramebuffer(this._texture, this.isCube);
  17452. }
  17453. };
  17454. RenderTargetTexture.prototype.clone = function () {
  17455. var textureSize = this.getSize();
  17456. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17457. // Base texture
  17458. newTexture.hasAlpha = this.hasAlpha;
  17459. newTexture.level = this.level;
  17460. // RenderTarget Texture
  17461. newTexture.coordinatesMode = this.coordinatesMode;
  17462. newTexture.renderList = this.renderList.slice(0);
  17463. return newTexture;
  17464. };
  17465. RenderTargetTexture.prototype.serialize = function () {
  17466. if (!this.name) {
  17467. return null;
  17468. }
  17469. var serializationObject = _super.prototype.serialize.call(this);
  17470. serializationObject.renderTargetSize = this.getRenderSize();
  17471. serializationObject.renderList = [];
  17472. for (var index = 0; index < this.renderList.length; index++) {
  17473. serializationObject.renderList.push(this.renderList[index].id);
  17474. }
  17475. return serializationObject;
  17476. };
  17477. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17478. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17479. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17480. return RenderTargetTexture;
  17481. })(BABYLON.Texture);
  17482. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17483. })(BABYLON || (BABYLON = {}));
  17484. var BABYLON;
  17485. (function (BABYLON) {
  17486. var ProceduralTexture = (function (_super) {
  17487. __extends(ProceduralTexture, _super);
  17488. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17489. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17490. _super.call(this, null, scene, !generateMipMaps);
  17491. this.isEnabled = true;
  17492. this._currentRefreshId = -1;
  17493. this._refreshRate = 1;
  17494. this._vertexDeclaration = [2];
  17495. this._vertexStrideSize = 2 * 4;
  17496. this._uniforms = new Array();
  17497. this._samplers = new Array();
  17498. this._textures = new Array();
  17499. this._floats = new Array();
  17500. this._floatsArrays = {};
  17501. this._colors3 = new Array();
  17502. this._colors4 = new Array();
  17503. this._vectors2 = new Array();
  17504. this._vectors3 = new Array();
  17505. this._matrices = new Array();
  17506. this._fallbackTextureUsed = false;
  17507. scene._proceduralTextures.push(this);
  17508. this.name = name;
  17509. this.isRenderTarget = true;
  17510. this._size = size;
  17511. this._generateMipMaps = generateMipMaps;
  17512. this.setFragment(fragment);
  17513. this._fallbackTexture = fallbackTexture;
  17514. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17515. // VBO
  17516. var vertices = [];
  17517. vertices.push(1, 1);
  17518. vertices.push(-1, 1);
  17519. vertices.push(-1, -1);
  17520. vertices.push(1, -1);
  17521. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17522. // Indices
  17523. var indices = [];
  17524. indices.push(0);
  17525. indices.push(1);
  17526. indices.push(2);
  17527. indices.push(0);
  17528. indices.push(2);
  17529. indices.push(3);
  17530. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17531. }
  17532. ProceduralTexture.prototype.reset = function () {
  17533. if (this._effect === undefined) {
  17534. return;
  17535. }
  17536. var engine = this.getScene().getEngine();
  17537. engine._releaseEffect(this._effect);
  17538. };
  17539. ProceduralTexture.prototype.isReady = function () {
  17540. var _this = this;
  17541. var engine = this.getScene().getEngine();
  17542. var shaders;
  17543. if (!this._fragment) {
  17544. return false;
  17545. }
  17546. if (this._fallbackTextureUsed) {
  17547. return true;
  17548. }
  17549. if (this._fragment.fragmentElement !== undefined) {
  17550. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17551. }
  17552. else {
  17553. shaders = { vertex: "procedural", fragment: this._fragment };
  17554. }
  17555. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17556. _this.releaseInternalTexture();
  17557. if (_this._fallbackTexture) {
  17558. _this._texture = _this._fallbackTexture._texture;
  17559. _this._texture.references++;
  17560. }
  17561. _this._fallbackTextureUsed = true;
  17562. });
  17563. return this._effect.isReady();
  17564. };
  17565. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17566. this._currentRefreshId = -1;
  17567. };
  17568. ProceduralTexture.prototype.setFragment = function (fragment) {
  17569. this._fragment = fragment;
  17570. };
  17571. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17572. get: function () {
  17573. return this._refreshRate;
  17574. },
  17575. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17576. set: function (value) {
  17577. this._refreshRate = value;
  17578. this.resetRefreshCounter();
  17579. },
  17580. enumerable: true,
  17581. configurable: true
  17582. });
  17583. ProceduralTexture.prototype._shouldRender = function () {
  17584. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17585. return false;
  17586. }
  17587. if (this._fallbackTextureUsed) {
  17588. return false;
  17589. }
  17590. if (this._currentRefreshId === -1) {
  17591. this._currentRefreshId = 1;
  17592. return true;
  17593. }
  17594. if (this.refreshRate === this._currentRefreshId) {
  17595. this._currentRefreshId = 1;
  17596. return true;
  17597. }
  17598. this._currentRefreshId++;
  17599. return false;
  17600. };
  17601. ProceduralTexture.prototype.getRenderSize = function () {
  17602. return this._size;
  17603. };
  17604. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17605. if (this._fallbackTextureUsed) {
  17606. return;
  17607. }
  17608. this.releaseInternalTexture();
  17609. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17610. };
  17611. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17612. if (this._uniforms.indexOf(uniformName) === -1) {
  17613. this._uniforms.push(uniformName);
  17614. }
  17615. };
  17616. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17617. if (this._samplers.indexOf(name) === -1) {
  17618. this._samplers.push(name);
  17619. }
  17620. this._textures[name] = texture;
  17621. return this;
  17622. };
  17623. ProceduralTexture.prototype.setFloat = function (name, value) {
  17624. this._checkUniform(name);
  17625. this._floats[name] = value;
  17626. return this;
  17627. };
  17628. ProceduralTexture.prototype.setFloats = function (name, value) {
  17629. this._checkUniform(name);
  17630. this._floatsArrays[name] = value;
  17631. return this;
  17632. };
  17633. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17634. this._checkUniform(name);
  17635. this._colors3[name] = value;
  17636. return this;
  17637. };
  17638. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17639. this._checkUniform(name);
  17640. this._colors4[name] = value;
  17641. return this;
  17642. };
  17643. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17644. this._checkUniform(name);
  17645. this._vectors2[name] = value;
  17646. return this;
  17647. };
  17648. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17649. this._checkUniform(name);
  17650. this._vectors3[name] = value;
  17651. return this;
  17652. };
  17653. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17654. this._checkUniform(name);
  17655. this._matrices[name] = value;
  17656. return this;
  17657. };
  17658. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17659. var scene = this.getScene();
  17660. var engine = scene.getEngine();
  17661. engine.bindFramebuffer(this._texture);
  17662. // Clear
  17663. engine.clear(scene.clearColor, true, true);
  17664. // Render
  17665. engine.enableEffect(this._effect);
  17666. engine.setState(false);
  17667. // Texture
  17668. for (var name in this._textures) {
  17669. this._effect.setTexture(name, this._textures[name]);
  17670. }
  17671. // Float
  17672. for (name in this._floats) {
  17673. this._effect.setFloat(name, this._floats[name]);
  17674. }
  17675. // Floats
  17676. for (name in this._floatsArrays) {
  17677. this._effect.setArray(name, this._floatsArrays[name]);
  17678. }
  17679. // Color3
  17680. for (name in this._colors3) {
  17681. this._effect.setColor3(name, this._colors3[name]);
  17682. }
  17683. // Color4
  17684. for (name in this._colors4) {
  17685. var color = this._colors4[name];
  17686. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17687. }
  17688. // Vector2
  17689. for (name in this._vectors2) {
  17690. this._effect.setVector2(name, this._vectors2[name]);
  17691. }
  17692. // Vector3
  17693. for (name in this._vectors3) {
  17694. this._effect.setVector3(name, this._vectors3[name]);
  17695. }
  17696. // Matrix
  17697. for (name in this._matrices) {
  17698. this._effect.setMatrix(name, this._matrices[name]);
  17699. }
  17700. // VBOs
  17701. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17702. // Draw order
  17703. engine.draw(true, 0, 6);
  17704. // Unbind
  17705. engine.unBindFramebuffer(this._texture);
  17706. };
  17707. ProceduralTexture.prototype.clone = function () {
  17708. var textureSize = this.getSize();
  17709. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17710. // Base texture
  17711. newTexture.hasAlpha = this.hasAlpha;
  17712. newTexture.level = this.level;
  17713. // RenderTarget Texture
  17714. newTexture.coordinatesMode = this.coordinatesMode;
  17715. return newTexture;
  17716. };
  17717. ProceduralTexture.prototype.dispose = function () {
  17718. var index = this.getScene()._proceduralTextures.indexOf(this);
  17719. if (index >= 0) {
  17720. this.getScene()._proceduralTextures.splice(index, 1);
  17721. }
  17722. _super.prototype.dispose.call(this);
  17723. };
  17724. return ProceduralTexture;
  17725. })(BABYLON.Texture);
  17726. BABYLON.ProceduralTexture = ProceduralTexture;
  17727. })(BABYLON || (BABYLON = {}));
  17728. var BABYLON;
  17729. (function (BABYLON) {
  17730. var MirrorTexture = (function (_super) {
  17731. __extends(MirrorTexture, _super);
  17732. function MirrorTexture(name, size, scene, generateMipMaps) {
  17733. var _this = this;
  17734. _super.call(this, name, size, scene, generateMipMaps, true);
  17735. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17736. this._transformMatrix = BABYLON.Matrix.Zero();
  17737. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17738. this.onBeforeRender = function () {
  17739. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17740. _this._savedViewMatrix = scene.getViewMatrix();
  17741. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17742. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17743. scene.clipPlane = _this.mirrorPlane;
  17744. scene.getEngine().cullBackFaces = false;
  17745. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17746. };
  17747. this.onAfterRender = function () {
  17748. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17749. scene.getEngine().cullBackFaces = true;
  17750. scene._mirroredCameraPosition = null;
  17751. delete scene.clipPlane;
  17752. };
  17753. }
  17754. MirrorTexture.prototype.clone = function () {
  17755. var textureSize = this.getSize();
  17756. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17757. // Base texture
  17758. newTexture.hasAlpha = this.hasAlpha;
  17759. newTexture.level = this.level;
  17760. // Mirror Texture
  17761. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17762. newTexture.renderList = this.renderList.slice(0);
  17763. return newTexture;
  17764. };
  17765. MirrorTexture.prototype.serialize = function () {
  17766. if (!this.name) {
  17767. return null;
  17768. }
  17769. var serializationObject = _super.prototype.serialize.call(this);
  17770. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17771. return serializationObject;
  17772. };
  17773. return MirrorTexture;
  17774. })(BABYLON.RenderTargetTexture);
  17775. BABYLON.MirrorTexture = MirrorTexture;
  17776. })(BABYLON || (BABYLON = {}));
  17777. var BABYLON;
  17778. (function (BABYLON) {
  17779. var DynamicTexture = (function (_super) {
  17780. __extends(DynamicTexture, _super);
  17781. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17783. _super.call(this, null, scene, !generateMipMaps);
  17784. this.name = name;
  17785. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17786. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17787. this._generateMipMaps = generateMipMaps;
  17788. if (options.getContext) {
  17789. this._canvas = options;
  17790. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17791. }
  17792. else {
  17793. this._canvas = document.createElement("canvas");
  17794. if (options.width) {
  17795. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17796. }
  17797. else {
  17798. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17799. }
  17800. }
  17801. var textureSize = this.getSize();
  17802. this._canvas.width = textureSize.width;
  17803. this._canvas.height = textureSize.height;
  17804. this._context = this._canvas.getContext("2d");
  17805. }
  17806. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17807. get: function () {
  17808. return true;
  17809. },
  17810. enumerable: true,
  17811. configurable: true
  17812. });
  17813. DynamicTexture.prototype.scale = function (ratio) {
  17814. var textureSize = this.getSize();
  17815. textureSize.width *= ratio;
  17816. textureSize.height *= ratio;
  17817. this._canvas.width = textureSize.width;
  17818. this._canvas.height = textureSize.height;
  17819. this.releaseInternalTexture();
  17820. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17821. };
  17822. DynamicTexture.prototype.getContext = function () {
  17823. return this._context;
  17824. };
  17825. DynamicTexture.prototype.clear = function () {
  17826. var size = this.getSize();
  17827. this._context.fillRect(0, 0, size.width, size.height);
  17828. };
  17829. DynamicTexture.prototype.update = function (invertY) {
  17830. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17831. };
  17832. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17833. if (update === void 0) { update = true; }
  17834. var size = this.getSize();
  17835. if (clearColor) {
  17836. this._context.fillStyle = clearColor;
  17837. this._context.fillRect(0, 0, size.width, size.height);
  17838. }
  17839. this._context.font = font;
  17840. if (x === null) {
  17841. var textSize = this._context.measureText(text);
  17842. x = (size.width - textSize.width) / 2;
  17843. }
  17844. this._context.fillStyle = color;
  17845. this._context.fillText(text, x, y);
  17846. if (update) {
  17847. this.update(invertY);
  17848. }
  17849. };
  17850. DynamicTexture.prototype.clone = function () {
  17851. var textureSize = this.getSize();
  17852. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17853. // Base texture
  17854. newTexture.hasAlpha = this.hasAlpha;
  17855. newTexture.level = this.level;
  17856. // Dynamic Texture
  17857. newTexture.wrapU = this.wrapU;
  17858. newTexture.wrapV = this.wrapV;
  17859. return newTexture;
  17860. };
  17861. return DynamicTexture;
  17862. })(BABYLON.Texture);
  17863. BABYLON.DynamicTexture = DynamicTexture;
  17864. })(BABYLON || (BABYLON = {}));
  17865. var BABYLON;
  17866. (function (BABYLON) {
  17867. var VideoTexture = (function (_super) {
  17868. __extends(VideoTexture, _super);
  17869. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17870. var _this = this;
  17871. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17872. if (invertY === void 0) { invertY = false; }
  17873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17874. _super.call(this, null, scene, !generateMipMaps, invertY);
  17875. this._autoLaunch = true;
  17876. this.name = name;
  17877. this.video = document.createElement("video");
  17878. this.video.autoplay = false;
  17879. this.video.loop = true;
  17880. this.video.addEventListener("canplaythrough", function () {
  17881. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17882. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17883. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17884. }
  17885. else {
  17886. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17887. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17888. generateMipMaps = false;
  17889. }
  17890. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17891. _this._texture.isReady = true;
  17892. });
  17893. urls.forEach(function (url) {
  17894. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17895. var source = document.createElement("source");
  17896. source.src = url;
  17897. _this.video.appendChild(source);
  17898. });
  17899. this._lastUpdate = BABYLON.Tools.Now;
  17900. }
  17901. VideoTexture.prototype.update = function () {
  17902. if (this._autoLaunch) {
  17903. this._autoLaunch = false;
  17904. this.video.play();
  17905. }
  17906. var now = BABYLON.Tools.Now;
  17907. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17908. return false;
  17909. }
  17910. this._lastUpdate = now;
  17911. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17912. return true;
  17913. };
  17914. return VideoTexture;
  17915. })(BABYLON.Texture);
  17916. BABYLON.VideoTexture = VideoTexture;
  17917. })(BABYLON || (BABYLON = {}));
  17918. var BABYLON;
  17919. (function (BABYLON) {
  17920. var CustomProceduralTexture = (function (_super) {
  17921. __extends(CustomProceduralTexture, _super);
  17922. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17923. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17924. this._animate = true;
  17925. this._time = 0;
  17926. this._texturePath = texturePath;
  17927. //Try to load json
  17928. this.loadJson(texturePath);
  17929. this.refreshRate = 1;
  17930. }
  17931. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17932. var _this = this;
  17933. var that = this;
  17934. function noConfigFile() {
  17935. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17936. try {
  17937. that.setFragment(that._texturePath);
  17938. }
  17939. catch (ex) {
  17940. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17941. }
  17942. }
  17943. var configFileUrl = jsonUrl + "/config.json";
  17944. var xhr = new XMLHttpRequest();
  17945. xhr.open("GET", configFileUrl, true);
  17946. xhr.addEventListener("load", function () {
  17947. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17948. try {
  17949. _this._config = JSON.parse(xhr.response);
  17950. _this.updateShaderUniforms();
  17951. _this.updateTextures();
  17952. _this.setFragment(_this._texturePath + "/custom");
  17953. _this._animate = _this._config.animate;
  17954. _this.refreshRate = _this._config.refreshrate;
  17955. }
  17956. catch (ex) {
  17957. noConfigFile();
  17958. }
  17959. }
  17960. else {
  17961. noConfigFile();
  17962. }
  17963. }, false);
  17964. xhr.addEventListener("error", function () {
  17965. noConfigFile();
  17966. }, false);
  17967. try {
  17968. xhr.send();
  17969. }
  17970. catch (ex) {
  17971. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17972. }
  17973. };
  17974. CustomProceduralTexture.prototype.isReady = function () {
  17975. if (!_super.prototype.isReady.call(this)) {
  17976. return false;
  17977. }
  17978. for (var name in this._textures) {
  17979. var texture = this._textures[name];
  17980. if (!texture.isReady()) {
  17981. return false;
  17982. }
  17983. }
  17984. return true;
  17985. };
  17986. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17987. if (this._animate) {
  17988. this._time += this.getScene().getAnimationRatio() * 0.03;
  17989. this.updateShaderUniforms();
  17990. }
  17991. _super.prototype.render.call(this, useCameraPostProcess);
  17992. };
  17993. CustomProceduralTexture.prototype.updateTextures = function () {
  17994. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17995. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17996. }
  17997. };
  17998. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17999. if (this._config) {
  18000. for (var j = 0; j < this._config.uniforms.length; j++) {
  18001. var uniform = this._config.uniforms[j];
  18002. switch (uniform.type) {
  18003. case "float":
  18004. this.setFloat(uniform.name, uniform.value);
  18005. break;
  18006. case "color3":
  18007. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18008. break;
  18009. case "color4":
  18010. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18011. break;
  18012. case "vector2":
  18013. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18014. break;
  18015. case "vector3":
  18016. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18017. break;
  18018. }
  18019. }
  18020. }
  18021. this.setFloat("time", this._time);
  18022. };
  18023. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18024. get: function () {
  18025. return this._animate;
  18026. },
  18027. set: function (value) {
  18028. this._animate = value;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. return CustomProceduralTexture;
  18034. })(BABYLON.ProceduralTexture);
  18035. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18036. })(BABYLON || (BABYLON = {}));
  18037. var BABYLON;
  18038. (function (BABYLON) {
  18039. var EffectFallbacks = (function () {
  18040. function EffectFallbacks() {
  18041. this._defines = {};
  18042. this._currentRank = 32;
  18043. this._maxRank = -1;
  18044. }
  18045. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18046. if (!this._defines[rank]) {
  18047. if (rank < this._currentRank) {
  18048. this._currentRank = rank;
  18049. }
  18050. if (rank > this._maxRank) {
  18051. this._maxRank = rank;
  18052. }
  18053. this._defines[rank] = new Array();
  18054. }
  18055. this._defines[rank].push(define);
  18056. };
  18057. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18058. this._meshRank = rank;
  18059. this._mesh = mesh;
  18060. if (rank > this._maxRank) {
  18061. this._maxRank = rank;
  18062. }
  18063. };
  18064. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18065. get: function () {
  18066. return this._currentRank <= this._maxRank;
  18067. },
  18068. enumerable: true,
  18069. configurable: true
  18070. });
  18071. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18072. var currentFallbacks = this._defines[this._currentRank];
  18073. for (var index = 0; index < currentFallbacks.length; index++) {
  18074. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18075. }
  18076. if (this._mesh && this._currentRank === this._meshRank) {
  18077. this._mesh.computeBonesUsingShaders = false;
  18078. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18079. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18080. }
  18081. this._currentRank++;
  18082. return currentDefines;
  18083. };
  18084. return EffectFallbacks;
  18085. })();
  18086. BABYLON.EffectFallbacks = EffectFallbacks;
  18087. var Effect = (function () {
  18088. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18089. var _this = this;
  18090. this._isReady = false;
  18091. this._compilationError = "";
  18092. this._valueCache = [];
  18093. this._engine = engine;
  18094. this.name = baseName;
  18095. this.defines = defines;
  18096. this._uniformsNames = uniformsNames.concat(samplers);
  18097. this._samplers = samplers;
  18098. this._attributesNames = attributesNames;
  18099. this.onError = onError;
  18100. this.onCompiled = onCompiled;
  18101. var vertexSource;
  18102. var fragmentSource;
  18103. if (baseName.vertexElement) {
  18104. vertexSource = document.getElementById(baseName.vertexElement);
  18105. if (!vertexSource) {
  18106. vertexSource = baseName.vertexElement;
  18107. }
  18108. }
  18109. else {
  18110. vertexSource = baseName.vertex || baseName;
  18111. }
  18112. if (baseName.fragmentElement) {
  18113. fragmentSource = document.getElementById(baseName.fragmentElement);
  18114. if (!fragmentSource) {
  18115. fragmentSource = baseName.fragmentElement;
  18116. }
  18117. }
  18118. else {
  18119. fragmentSource = baseName.fragment || baseName;
  18120. }
  18121. this._loadVertexShader(vertexSource, function (vertexCode) {
  18122. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18123. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18124. });
  18125. });
  18126. }
  18127. // Properties
  18128. Effect.prototype.isReady = function () {
  18129. return this._isReady;
  18130. };
  18131. Effect.prototype.getProgram = function () {
  18132. return this._program;
  18133. };
  18134. Effect.prototype.getAttributesNames = function () {
  18135. return this._attributesNames;
  18136. };
  18137. Effect.prototype.getAttributeLocation = function (index) {
  18138. return this._attributes[index];
  18139. };
  18140. Effect.prototype.getAttributeLocationByName = function (name) {
  18141. var index = this._attributesNames.indexOf(name);
  18142. return this._attributes[index];
  18143. };
  18144. Effect.prototype.getAttributesCount = function () {
  18145. return this._attributes.length;
  18146. };
  18147. Effect.prototype.getUniformIndex = function (uniformName) {
  18148. return this._uniformsNames.indexOf(uniformName);
  18149. };
  18150. Effect.prototype.getUniform = function (uniformName) {
  18151. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18152. };
  18153. Effect.prototype.getSamplers = function () {
  18154. return this._samplers;
  18155. };
  18156. Effect.prototype.getCompilationError = function () {
  18157. return this._compilationError;
  18158. };
  18159. // Methods
  18160. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18161. // DOM element ?
  18162. if (vertex instanceof HTMLElement) {
  18163. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18164. callback(vertexCode);
  18165. return;
  18166. }
  18167. // Is in local store ?
  18168. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18169. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18170. return;
  18171. }
  18172. var vertexShaderUrl;
  18173. if (vertex[0] === "." || vertex[0] === "/") {
  18174. vertexShaderUrl = vertex;
  18175. }
  18176. else {
  18177. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18178. }
  18179. // Vertex shader
  18180. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18181. };
  18182. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18183. // DOM element ?
  18184. if (fragment instanceof HTMLElement) {
  18185. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18186. callback(fragmentCode);
  18187. return;
  18188. }
  18189. // Is in local store ?
  18190. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18191. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18192. return;
  18193. }
  18194. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18195. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18196. return;
  18197. }
  18198. var fragmentShaderUrl;
  18199. if (fragment[0] === "." || fragment[0] === "/") {
  18200. fragmentShaderUrl = fragment;
  18201. }
  18202. else {
  18203. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18204. }
  18205. // Fragment shader
  18206. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18207. };
  18208. Effect.prototype._dumpShadersName = function () {
  18209. if (this.name.vertexElement) {
  18210. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18211. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18212. }
  18213. else if (this.name.vertex) {
  18214. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18215. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18216. }
  18217. else {
  18218. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18219. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18220. }
  18221. };
  18222. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18223. try {
  18224. var engine = this._engine;
  18225. if (!engine.getCaps().highPrecisionShaderSupported) {
  18226. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18227. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18228. }
  18229. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18230. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18231. this._attributes = engine.getAttributes(this._program, attributesNames);
  18232. for (var index = 0; index < this._samplers.length; index++) {
  18233. var sampler = this.getUniform(this._samplers[index]);
  18234. if (sampler == null) {
  18235. this._samplers.splice(index, 1);
  18236. index--;
  18237. }
  18238. }
  18239. engine.bindSamplers(this);
  18240. this._isReady = true;
  18241. if (this.onCompiled) {
  18242. this.onCompiled(this);
  18243. }
  18244. }
  18245. catch (e) {
  18246. // Is it a problem with precision?
  18247. if (e.message.indexOf("highp") !== -1) {
  18248. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18249. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18250. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18251. return;
  18252. }
  18253. // Let's go through fallbacks then
  18254. if (fallbacks && fallbacks.isMoreFallbacks) {
  18255. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18256. this._dumpShadersName();
  18257. defines = fallbacks.reduce(defines);
  18258. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18259. }
  18260. else {
  18261. BABYLON.Tools.Error("Unable to compile effect: ");
  18262. this._dumpShadersName();
  18263. BABYLON.Tools.Error("Defines: " + defines);
  18264. BABYLON.Tools.Error("Error: " + e.message);
  18265. this._compilationError = e.message;
  18266. if (this.onError) {
  18267. this.onError(this, this._compilationError);
  18268. }
  18269. }
  18270. }
  18271. };
  18272. Object.defineProperty(Effect.prototype, "isSupported", {
  18273. get: function () {
  18274. return this._compilationError === "";
  18275. },
  18276. enumerable: true,
  18277. configurable: true
  18278. });
  18279. Effect.prototype._bindTexture = function (channel, texture) {
  18280. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18281. };
  18282. Effect.prototype.setTexture = function (channel, texture) {
  18283. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18284. };
  18285. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18286. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18287. };
  18288. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18289. if (!this._valueCache[uniformName]) {
  18290. this._valueCache[uniformName] = new BABYLON.Matrix();
  18291. }
  18292. for (var index = 0; index < 16; index++) {
  18293. this._valueCache[uniformName].m[index] = matrix.m[index];
  18294. }
  18295. };
  18296. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18297. if (!this._valueCache[uniformName]) {
  18298. this._valueCache[uniformName] = [x, y];
  18299. return;
  18300. }
  18301. this._valueCache[uniformName][0] = x;
  18302. this._valueCache[uniformName][1] = y;
  18303. };
  18304. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18305. if (!this._valueCache[uniformName]) {
  18306. this._valueCache[uniformName] = [x, y, z];
  18307. return;
  18308. }
  18309. this._valueCache[uniformName][0] = x;
  18310. this._valueCache[uniformName][1] = y;
  18311. this._valueCache[uniformName][2] = z;
  18312. };
  18313. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18314. if (!this._valueCache[uniformName]) {
  18315. this._valueCache[uniformName] = [x, y, z, w];
  18316. return;
  18317. }
  18318. this._valueCache[uniformName][0] = x;
  18319. this._valueCache[uniformName][1] = y;
  18320. this._valueCache[uniformName][2] = z;
  18321. this._valueCache[uniformName][3] = w;
  18322. };
  18323. Effect.prototype.setArray = function (uniformName, array) {
  18324. this._engine.setArray(this.getUniform(uniformName), array);
  18325. return this;
  18326. };
  18327. Effect.prototype.setArray2 = function (uniformName, array) {
  18328. this._engine.setArray2(this.getUniform(uniformName), array);
  18329. return this;
  18330. };
  18331. Effect.prototype.setArray3 = function (uniformName, array) {
  18332. this._engine.setArray3(this.getUniform(uniformName), array);
  18333. return this;
  18334. };
  18335. Effect.prototype.setArray4 = function (uniformName, array) {
  18336. this._engine.setArray4(this.getUniform(uniformName), array);
  18337. return this;
  18338. };
  18339. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18340. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18341. return this;
  18342. };
  18343. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18344. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18345. return this;
  18346. this._cacheMatrix(uniformName, matrix);
  18347. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18348. return this;
  18349. };
  18350. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18351. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18352. return this;
  18353. };
  18354. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18355. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18356. return this;
  18357. };
  18358. Effect.prototype.setFloat = function (uniformName, value) {
  18359. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18360. return this;
  18361. this._valueCache[uniformName] = value;
  18362. this._engine.setFloat(this.getUniform(uniformName), value);
  18363. return this;
  18364. };
  18365. Effect.prototype.setBool = function (uniformName, bool) {
  18366. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18367. return this;
  18368. this._valueCache[uniformName] = bool;
  18369. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18370. return this;
  18371. };
  18372. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18373. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18374. return this;
  18375. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18376. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18377. return this;
  18378. };
  18379. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18380. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18381. return this;
  18382. this._cacheFloat2(uniformName, x, y);
  18383. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18384. return this;
  18385. };
  18386. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18387. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18388. return this;
  18389. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18390. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18391. return this;
  18392. };
  18393. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18394. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18395. return this;
  18396. this._cacheFloat3(uniformName, x, y, z);
  18397. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18398. return this;
  18399. };
  18400. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18401. 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)
  18402. return this;
  18403. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18404. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18405. return this;
  18406. };
  18407. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18408. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18409. return this;
  18410. this._cacheFloat4(uniformName, x, y, z, w);
  18411. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18412. return this;
  18413. };
  18414. Effect.prototype.setColor3 = function (uniformName, color3) {
  18415. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18416. return this;
  18417. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18418. this._engine.setColor3(this.getUniform(uniformName), color3);
  18419. return this;
  18420. };
  18421. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18422. 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)
  18423. return this;
  18424. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18425. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18426. return this;
  18427. };
  18428. // Statics
  18429. Effect.ShadersStore = {};
  18430. return Effect;
  18431. })();
  18432. BABYLON.Effect = Effect;
  18433. })(BABYLON || (BABYLON = {}));
  18434. var BABYLON;
  18435. (function (BABYLON) {
  18436. var MaterialDefines = (function () {
  18437. function MaterialDefines() {
  18438. }
  18439. MaterialDefines.prototype.isEqual = function (other) {
  18440. for (var index = 0; index < this._keys.length; index++) {
  18441. var prop = this._keys[index];
  18442. if (this[prop] !== other[prop]) {
  18443. return false;
  18444. }
  18445. }
  18446. return true;
  18447. };
  18448. MaterialDefines.prototype.cloneTo = function (other) {
  18449. for (var index = 0; index < this._keys.length; index++) {
  18450. var prop = this._keys[index];
  18451. other[prop] = this[prop];
  18452. }
  18453. };
  18454. MaterialDefines.prototype.reset = function () {
  18455. for (var index = 0; index < this._keys.length; index++) {
  18456. var prop = this._keys[index];
  18457. if (typeof (this[prop]) === "number") {
  18458. this[prop] = 0;
  18459. }
  18460. else {
  18461. this[prop] = false;
  18462. }
  18463. }
  18464. };
  18465. MaterialDefines.prototype.toString = function () {
  18466. var result = "";
  18467. for (var index = 0; index < this._keys.length; index++) {
  18468. var prop = this._keys[index];
  18469. if (typeof (this[prop]) === "number") {
  18470. result += "#define " + prop + " " + this[prop] + "\n";
  18471. }
  18472. else if (this[prop]) {
  18473. result += "#define " + prop + "\n";
  18474. }
  18475. }
  18476. return result;
  18477. };
  18478. return MaterialDefines;
  18479. })();
  18480. BABYLON.MaterialDefines = MaterialDefines;
  18481. var Material = (function () {
  18482. function Material(name, scene, doNotAdd) {
  18483. this.name = name;
  18484. this.checkReadyOnEveryCall = false;
  18485. this.checkReadyOnlyOnce = false;
  18486. this.state = "";
  18487. this.alpha = 1.0;
  18488. this.backFaceCulling = true;
  18489. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18490. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18491. this.disableDepthWrite = false;
  18492. this.fogEnabled = true;
  18493. this._wasPreviouslyReady = false;
  18494. this._fillMode = Material.TriangleFillMode;
  18495. this.pointSize = 1.0;
  18496. this.zOffset = 0;
  18497. this.id = name;
  18498. this._scene = scene;
  18499. if (!doNotAdd) {
  18500. scene.materials.push(this);
  18501. }
  18502. }
  18503. Object.defineProperty(Material, "TriangleFillMode", {
  18504. get: function () {
  18505. return Material._TriangleFillMode;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. Object.defineProperty(Material, "WireFrameFillMode", {
  18511. get: function () {
  18512. return Material._WireFrameFillMode;
  18513. },
  18514. enumerable: true,
  18515. configurable: true
  18516. });
  18517. Object.defineProperty(Material, "PointFillMode", {
  18518. get: function () {
  18519. return Material._PointFillMode;
  18520. },
  18521. enumerable: true,
  18522. configurable: true
  18523. });
  18524. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18525. get: function () {
  18526. return Material._ClockWiseSideOrientation;
  18527. },
  18528. enumerable: true,
  18529. configurable: true
  18530. });
  18531. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18532. get: function () {
  18533. return Material._CounterClockWiseSideOrientation;
  18534. },
  18535. enumerable: true,
  18536. configurable: true
  18537. });
  18538. Object.defineProperty(Material.prototype, "wireframe", {
  18539. get: function () {
  18540. return this._fillMode === Material.WireFrameFillMode;
  18541. },
  18542. set: function (value) {
  18543. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(Material.prototype, "pointsCloud", {
  18549. get: function () {
  18550. return this._fillMode === Material.PointFillMode;
  18551. },
  18552. set: function (value) {
  18553. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. Object.defineProperty(Material.prototype, "fillMode", {
  18559. get: function () {
  18560. return this._fillMode;
  18561. },
  18562. set: function (value) {
  18563. this._fillMode = value;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. Material.prototype.isReady = function (mesh, useInstances) {
  18569. return true;
  18570. };
  18571. Material.prototype.getEffect = function () {
  18572. return this._effect;
  18573. };
  18574. Material.prototype.getScene = function () {
  18575. return this._scene;
  18576. };
  18577. Material.prototype.needAlphaBlending = function () {
  18578. return (this.alpha < 1.0);
  18579. };
  18580. Material.prototype.needAlphaTesting = function () {
  18581. return false;
  18582. };
  18583. Material.prototype.getAlphaTestTexture = function () {
  18584. return null;
  18585. };
  18586. Material.prototype.trackCreation = function (onCompiled, onError) {
  18587. };
  18588. Material.prototype.markDirty = function () {
  18589. this._wasPreviouslyReady = false;
  18590. };
  18591. Material.prototype._preBind = function () {
  18592. var engine = this._scene.getEngine();
  18593. engine.enableEffect(this._effect);
  18594. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18595. };
  18596. Material.prototype.bind = function (world, mesh) {
  18597. this._scene._cachedMaterial = this;
  18598. if (this.onBind) {
  18599. this.onBind(this, mesh);
  18600. }
  18601. if (this.disableDepthWrite) {
  18602. var engine = this._scene.getEngine();
  18603. this._cachedDepthWriteState = engine.getDepthWrite();
  18604. engine.setDepthWrite(false);
  18605. }
  18606. };
  18607. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18608. };
  18609. Material.prototype.unbind = function () {
  18610. if (this.disableDepthWrite) {
  18611. var engine = this._scene.getEngine();
  18612. engine.setDepthWrite(this._cachedDepthWriteState);
  18613. }
  18614. };
  18615. Material.prototype.clone = function (name) {
  18616. return null;
  18617. };
  18618. Material.prototype.getBindedMeshes = function () {
  18619. var result = new Array();
  18620. for (var index = 0; index < this._scene.meshes.length; index++) {
  18621. var mesh = this._scene.meshes[index];
  18622. if (mesh.material === this) {
  18623. result.push(mesh);
  18624. }
  18625. }
  18626. return result;
  18627. };
  18628. Material.prototype.dispose = function (forceDisposeEffect) {
  18629. // Animations
  18630. this.getScene().stopAnimation(this);
  18631. // Remove from scene
  18632. var index = this._scene.materials.indexOf(this);
  18633. if (index >= 0) {
  18634. this._scene.materials.splice(index, 1);
  18635. }
  18636. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18637. if (forceDisposeEffect && this._effect) {
  18638. this._scene.getEngine()._releaseEffect(this._effect);
  18639. this._effect = null;
  18640. }
  18641. // Remove from meshes
  18642. for (index = 0; index < this._scene.meshes.length; index++) {
  18643. var mesh = this._scene.meshes[index];
  18644. if (mesh.material === this) {
  18645. mesh.material = null;
  18646. }
  18647. }
  18648. // Callback
  18649. if (this.onDispose) {
  18650. this.onDispose();
  18651. }
  18652. };
  18653. Material.prototype.copyTo = function (other) {
  18654. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18655. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18656. other.alpha = this.alpha;
  18657. other.fillMode = this.fillMode;
  18658. other.backFaceCulling = this.backFaceCulling;
  18659. other.fogEnabled = this.fogEnabled;
  18660. other.wireframe = this.wireframe;
  18661. other.zOffset = this.zOffset;
  18662. other.alphaMode = this.alphaMode;
  18663. other.sideOrientation = this.sideOrientation;
  18664. other.disableDepthWrite = this.disableDepthWrite;
  18665. other.pointSize = this.pointSize;
  18666. other.pointsCloud = this.pointsCloud;
  18667. };
  18668. Material.prototype.serialize = function () {
  18669. var serializationObject = {};
  18670. serializationObject.name = this.name;
  18671. serializationObject.alpha = this.alpha;
  18672. serializationObject.id = this.id;
  18673. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18674. serializationObject.backFaceCulling = this.backFaceCulling;
  18675. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18676. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18677. return serializationObject;
  18678. };
  18679. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18680. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18681. multiMaterial.id = parsedMultiMaterial.id;
  18682. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18683. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18684. var subMatId = parsedMultiMaterial.materials[matIndex];
  18685. if (subMatId) {
  18686. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18687. }
  18688. else {
  18689. multiMaterial.subMaterials.push(null);
  18690. }
  18691. }
  18692. return multiMaterial;
  18693. };
  18694. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18695. if (!parsedMaterial.customType) {
  18696. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18697. }
  18698. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18699. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18700. ;
  18701. };
  18702. Material._TriangleFillMode = 0;
  18703. Material._WireFrameFillMode = 1;
  18704. Material._PointFillMode = 2;
  18705. Material._ClockWiseSideOrientation = 0;
  18706. Material._CounterClockWiseSideOrientation = 1;
  18707. return Material;
  18708. })();
  18709. BABYLON.Material = Material;
  18710. })(BABYLON || (BABYLON = {}));
  18711. var BABYLON;
  18712. (function (BABYLON) {
  18713. var maxSimultaneousLights = 4;
  18714. var FresnelParameters = (function () {
  18715. function FresnelParameters() {
  18716. this.isEnabled = true;
  18717. this.leftColor = BABYLON.Color3.White();
  18718. this.rightColor = BABYLON.Color3.Black();
  18719. this.bias = 0;
  18720. this.power = 1;
  18721. }
  18722. FresnelParameters.prototype.clone = function () {
  18723. var newFresnelParameters = new FresnelParameters();
  18724. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18725. return new FresnelParameters;
  18726. };
  18727. FresnelParameters.prototype.serialize = function () {
  18728. var serializationObject = {};
  18729. serializationObject.isEnabled = this.isEnabled;
  18730. serializationObject.leftColor = this.leftColor;
  18731. serializationObject.rightColor = this.rightColor;
  18732. serializationObject.bias = this.bias;
  18733. serializationObject.power = this.power;
  18734. return serializationObject;
  18735. };
  18736. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18737. var fresnelParameters = new FresnelParameters();
  18738. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18739. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18740. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18741. fresnelParameters.bias = parsedFresnelParameters.bias;
  18742. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18743. return fresnelParameters;
  18744. };
  18745. return FresnelParameters;
  18746. })();
  18747. BABYLON.FresnelParameters = FresnelParameters;
  18748. var StandardMaterialDefines = (function (_super) {
  18749. __extends(StandardMaterialDefines, _super);
  18750. function StandardMaterialDefines() {
  18751. _super.call(this);
  18752. this.DIFFUSE = false;
  18753. this.AMBIENT = false;
  18754. this.OPACITY = false;
  18755. this.OPACITYRGB = false;
  18756. this.REFLECTION = false;
  18757. this.EMISSIVE = false;
  18758. this.SPECULAR = false;
  18759. this.BUMP = false;
  18760. this.SPECULAROVERALPHA = false;
  18761. this.CLIPPLANE = false;
  18762. this.ALPHATEST = false;
  18763. this.ALPHAFROMDIFFUSE = false;
  18764. this.POINTSIZE = false;
  18765. this.FOG = false;
  18766. this.LIGHT0 = false;
  18767. this.LIGHT1 = false;
  18768. this.LIGHT2 = false;
  18769. this.LIGHT3 = false;
  18770. this.SPOTLIGHT0 = false;
  18771. this.SPOTLIGHT1 = false;
  18772. this.SPOTLIGHT2 = false;
  18773. this.SPOTLIGHT3 = false;
  18774. this.HEMILIGHT0 = false;
  18775. this.HEMILIGHT1 = false;
  18776. this.HEMILIGHT2 = false;
  18777. this.HEMILIGHT3 = false;
  18778. this.POINTLIGHT0 = false;
  18779. this.POINTLIGHT1 = false;
  18780. this.POINTLIGHT2 = false;
  18781. this.POINTLIGHT3 = false;
  18782. this.DIRLIGHT0 = false;
  18783. this.DIRLIGHT1 = false;
  18784. this.DIRLIGHT2 = false;
  18785. this.DIRLIGHT3 = false;
  18786. this.SPECULARTERM = false;
  18787. this.SHADOW0 = false;
  18788. this.SHADOW1 = false;
  18789. this.SHADOW2 = false;
  18790. this.SHADOW3 = false;
  18791. this.SHADOWS = false;
  18792. this.SHADOWVSM0 = false;
  18793. this.SHADOWVSM1 = false;
  18794. this.SHADOWVSM2 = false;
  18795. this.SHADOWVSM3 = false;
  18796. this.SHADOWPCF0 = false;
  18797. this.SHADOWPCF1 = false;
  18798. this.SHADOWPCF2 = false;
  18799. this.SHADOWPCF3 = false;
  18800. this.DIFFUSEFRESNEL = false;
  18801. this.OPACITYFRESNEL = false;
  18802. this.REFLECTIONFRESNEL = false;
  18803. this.EMISSIVEFRESNEL = false;
  18804. this.FRESNEL = false;
  18805. this.NORMAL = false;
  18806. this.UV1 = false;
  18807. this.UV2 = false;
  18808. this.VERTEXCOLOR = false;
  18809. this.VERTEXALPHA = false;
  18810. this.NUM_BONE_INFLUENCERS = 0;
  18811. this.BonesPerMesh = 0;
  18812. this.INSTANCES = false;
  18813. this.GLOSSINESS = false;
  18814. this.ROUGHNESS = false;
  18815. this.EMISSIVEASILLUMINATION = false;
  18816. this.LINKEMISSIVEWITHDIFFUSE = false;
  18817. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18818. this.LIGHTMAP = false;
  18819. this.USELIGHTMAPASSHADOWMAP = false;
  18820. this.REFLECTIONMAP_3D = false;
  18821. this.REFLECTIONMAP_SPHERICAL = false;
  18822. this.REFLECTIONMAP_PLANAR = false;
  18823. this.REFLECTIONMAP_CUBIC = false;
  18824. this.REFLECTIONMAP_PROJECTION = false;
  18825. this.REFLECTIONMAP_SKYBOX = false;
  18826. this.REFLECTIONMAP_EXPLICIT = false;
  18827. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18828. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18829. this.INVERTCUBICMAP = false;
  18830. this.LOGARITHMICDEPTH = false;
  18831. this._keys = Object.keys(this);
  18832. }
  18833. return StandardMaterialDefines;
  18834. })(BABYLON.MaterialDefines);
  18835. var StandardMaterial = (function (_super) {
  18836. __extends(StandardMaterial, _super);
  18837. function StandardMaterial(name, scene) {
  18838. var _this = this;
  18839. _super.call(this, name, scene);
  18840. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18841. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18842. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18843. this.specularPower = 64;
  18844. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18845. this.useAlphaFromDiffuseTexture = false;
  18846. this.useEmissiveAsIllumination = false;
  18847. this.linkEmissiveWithDiffuse = false;
  18848. this.useReflectionFresnelFromSpecular = false;
  18849. this.useSpecularOverAlpha = true;
  18850. this.disableLighting = false;
  18851. this.roughness = 0;
  18852. this.useLightmapAsShadowmap = false;
  18853. this.useGlossinessFromSpecularMapAlpha = false;
  18854. this._renderTargets = new BABYLON.SmartArray(16);
  18855. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18856. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18857. this._defines = new StandardMaterialDefines();
  18858. this._cachedDefines = new StandardMaterialDefines();
  18859. this._cachedDefines.BonesPerMesh = -1;
  18860. this.getRenderTargetTextures = function () {
  18861. _this._renderTargets.reset();
  18862. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18863. _this._renderTargets.push(_this.reflectionTexture);
  18864. }
  18865. return _this._renderTargets;
  18866. };
  18867. }
  18868. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18869. get: function () {
  18870. return this._useLogarithmicDepth;
  18871. },
  18872. set: function (value) {
  18873. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18874. },
  18875. enumerable: true,
  18876. configurable: true
  18877. });
  18878. StandardMaterial.prototype.needAlphaBlending = function () {
  18879. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18880. };
  18881. StandardMaterial.prototype.needAlphaTesting = function () {
  18882. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18883. };
  18884. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18885. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18886. };
  18887. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18888. return this.diffuseTexture;
  18889. };
  18890. // Methods
  18891. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18892. if (!mesh) {
  18893. return true;
  18894. }
  18895. if (this._defines.INSTANCES !== useInstances) {
  18896. return false;
  18897. }
  18898. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18899. return true;
  18900. }
  18901. return false;
  18902. };
  18903. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18904. var lightIndex = 0;
  18905. var needNormals = false;
  18906. for (var index = 0; index < scene.lights.length; index++) {
  18907. var light = scene.lights[index];
  18908. if (!light.isEnabled()) {
  18909. continue;
  18910. }
  18911. // Excluded check
  18912. if (light._excludedMeshesIds.length > 0) {
  18913. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18914. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18915. if (excludedMesh) {
  18916. light.excludedMeshes.push(excludedMesh);
  18917. }
  18918. }
  18919. light._excludedMeshesIds = [];
  18920. }
  18921. // Included check
  18922. if (light._includedOnlyMeshesIds.length > 0) {
  18923. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18924. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18925. if (includedOnlyMesh) {
  18926. light.includedOnlyMeshes.push(includedOnlyMesh);
  18927. }
  18928. }
  18929. light._includedOnlyMeshesIds = [];
  18930. }
  18931. if (!light.canAffectMesh(mesh)) {
  18932. continue;
  18933. }
  18934. needNormals = true;
  18935. defines["LIGHT" + lightIndex] = true;
  18936. var type;
  18937. if (light instanceof BABYLON.SpotLight) {
  18938. type = "SPOTLIGHT" + lightIndex;
  18939. }
  18940. else if (light instanceof BABYLON.HemisphericLight) {
  18941. type = "HEMILIGHT" + lightIndex;
  18942. }
  18943. else if (light instanceof BABYLON.PointLight) {
  18944. type = "POINTLIGHT" + lightIndex;
  18945. }
  18946. else {
  18947. type = "DIRLIGHT" + lightIndex;
  18948. }
  18949. defines[type] = true;
  18950. // Specular
  18951. if (!light.specular.equalsFloats(0, 0, 0)) {
  18952. defines["SPECULARTERM"] = true;
  18953. }
  18954. // Shadows
  18955. if (scene.shadowsEnabled) {
  18956. var shadowGenerator = light.getShadowGenerator();
  18957. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18958. defines["SHADOW" + lightIndex] = true;
  18959. defines["SHADOWS"] = true;
  18960. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18961. defines["SHADOWVSM" + lightIndex] = true;
  18962. }
  18963. if (shadowGenerator.usePoissonSampling) {
  18964. defines["SHADOWPCF" + lightIndex] = true;
  18965. }
  18966. }
  18967. }
  18968. lightIndex++;
  18969. if (lightIndex === maxSimultaneousLights)
  18970. break;
  18971. }
  18972. return needNormals;
  18973. };
  18974. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18975. var lightIndex = 0;
  18976. for (var index = 0; index < scene.lights.length; index++) {
  18977. var light = scene.lights[index];
  18978. if (!light.isEnabled()) {
  18979. continue;
  18980. }
  18981. if (!light.canAffectMesh(mesh)) {
  18982. continue;
  18983. }
  18984. if (light instanceof BABYLON.PointLight) {
  18985. // Point Light
  18986. light.transferToEffect(effect, "vLightData" + lightIndex);
  18987. }
  18988. else if (light instanceof BABYLON.DirectionalLight) {
  18989. // Directional Light
  18990. light.transferToEffect(effect, "vLightData" + lightIndex);
  18991. }
  18992. else if (light instanceof BABYLON.SpotLight) {
  18993. // Spot Light
  18994. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18995. }
  18996. else if (light instanceof BABYLON.HemisphericLight) {
  18997. // Hemispheric Light
  18998. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18999. }
  19000. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19001. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19002. if (defines["SPECULARTERM"]) {
  19003. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19004. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19005. }
  19006. // Shadows
  19007. if (scene.shadowsEnabled) {
  19008. var shadowGenerator = light.getShadowGenerator();
  19009. if (mesh.receiveShadows && shadowGenerator) {
  19010. if (!light.needCube()) {
  19011. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19012. }
  19013. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19014. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19015. }
  19016. }
  19017. lightIndex++;
  19018. if (lightIndex === maxSimultaneousLights)
  19019. break;
  19020. }
  19021. };
  19022. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19023. if (this.checkReadyOnlyOnce) {
  19024. if (this._wasPreviouslyReady) {
  19025. return true;
  19026. }
  19027. }
  19028. var scene = this.getScene();
  19029. if (!this.checkReadyOnEveryCall) {
  19030. if (this._renderId === scene.getRenderId()) {
  19031. if (this._checkCache(scene, mesh, useInstances)) {
  19032. return true;
  19033. }
  19034. }
  19035. }
  19036. var engine = scene.getEngine();
  19037. var needNormals = false;
  19038. var needUVs = false;
  19039. this._defines.reset();
  19040. // Textures
  19041. if (scene.texturesEnabled) {
  19042. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19043. if (!this.diffuseTexture.isReady()) {
  19044. return false;
  19045. }
  19046. else {
  19047. needUVs = true;
  19048. this._defines.DIFFUSE = true;
  19049. }
  19050. }
  19051. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19052. if (!this.ambientTexture.isReady()) {
  19053. return false;
  19054. }
  19055. else {
  19056. needUVs = true;
  19057. this._defines.AMBIENT = true;
  19058. }
  19059. }
  19060. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19061. if (!this.opacityTexture.isReady()) {
  19062. return false;
  19063. }
  19064. else {
  19065. needUVs = true;
  19066. this._defines.OPACITY = true;
  19067. if (this.opacityTexture.getAlphaFromRGB) {
  19068. this._defines.OPACITYRGB = true;
  19069. }
  19070. }
  19071. }
  19072. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19073. if (!this.reflectionTexture.isReady()) {
  19074. return false;
  19075. }
  19076. else {
  19077. needNormals = true;
  19078. this._defines.REFLECTION = true;
  19079. if (this.roughness > 0) {
  19080. this._defines.ROUGHNESS = true;
  19081. }
  19082. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19083. this._defines.INVERTCUBICMAP = true;
  19084. }
  19085. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19086. switch (this.reflectionTexture.coordinatesMode) {
  19087. case BABYLON.Texture.CUBIC_MODE:
  19088. case BABYLON.Texture.INVCUBIC_MODE:
  19089. this._defines.REFLECTIONMAP_CUBIC = true;
  19090. break;
  19091. case BABYLON.Texture.EXPLICIT_MODE:
  19092. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19093. break;
  19094. case BABYLON.Texture.PLANAR_MODE:
  19095. this._defines.REFLECTIONMAP_PLANAR = true;
  19096. break;
  19097. case BABYLON.Texture.PROJECTION_MODE:
  19098. this._defines.REFLECTIONMAP_PROJECTION = true;
  19099. break;
  19100. case BABYLON.Texture.SKYBOX_MODE:
  19101. this._defines.REFLECTIONMAP_SKYBOX = true;
  19102. break;
  19103. case BABYLON.Texture.SPHERICAL_MODE:
  19104. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19105. break;
  19106. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19107. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19108. break;
  19109. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19110. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19111. break;
  19112. }
  19113. }
  19114. }
  19115. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19116. if (!this.emissiveTexture.isReady()) {
  19117. return false;
  19118. }
  19119. else {
  19120. needUVs = true;
  19121. this._defines.EMISSIVE = true;
  19122. }
  19123. }
  19124. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19125. if (!this.lightmapTexture.isReady()) {
  19126. return false;
  19127. }
  19128. else {
  19129. needUVs = true;
  19130. this._defines.LIGHTMAP = true;
  19131. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19132. }
  19133. }
  19134. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19135. if (!this.specularTexture.isReady()) {
  19136. return false;
  19137. }
  19138. else {
  19139. needUVs = true;
  19140. this._defines.SPECULAR = true;
  19141. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19142. }
  19143. }
  19144. }
  19145. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19146. if (!this.bumpTexture.isReady()) {
  19147. return false;
  19148. }
  19149. else {
  19150. needUVs = true;
  19151. this._defines.BUMP = true;
  19152. }
  19153. }
  19154. // Effect
  19155. if (scene.clipPlane) {
  19156. this._defines.CLIPPLANE = true;
  19157. }
  19158. if (engine.getAlphaTesting()) {
  19159. this._defines.ALPHATEST = true;
  19160. }
  19161. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19162. this._defines.ALPHAFROMDIFFUSE = true;
  19163. }
  19164. if (this.useEmissiveAsIllumination) {
  19165. this._defines.EMISSIVEASILLUMINATION = true;
  19166. }
  19167. if (this.linkEmissiveWithDiffuse) {
  19168. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19169. }
  19170. if (this.useReflectionFresnelFromSpecular) {
  19171. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19172. }
  19173. if (this.useLogarithmicDepth) {
  19174. this._defines.LOGARITHMICDEPTH = true;
  19175. }
  19176. // Point size
  19177. if (this.pointsCloud || scene.forcePointsCloud) {
  19178. this._defines.POINTSIZE = true;
  19179. }
  19180. // Fog
  19181. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19182. this._defines.FOG = true;
  19183. }
  19184. if (scene.lightsEnabled && !this.disableLighting) {
  19185. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19186. }
  19187. if (StandardMaterial.FresnelEnabled) {
  19188. // Fresnel
  19189. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19190. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19191. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19192. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19193. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19194. this._defines.DIFFUSEFRESNEL = true;
  19195. }
  19196. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19197. this._defines.OPACITYFRESNEL = true;
  19198. }
  19199. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19200. this._defines.REFLECTIONFRESNEL = true;
  19201. }
  19202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19203. this._defines.EMISSIVEFRESNEL = true;
  19204. }
  19205. needNormals = true;
  19206. this._defines.FRESNEL = true;
  19207. }
  19208. }
  19209. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19210. this._defines.SPECULAROVERALPHA = true;
  19211. }
  19212. // Attribs
  19213. if (mesh) {
  19214. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19215. this._defines.NORMAL = true;
  19216. }
  19217. if (needUVs) {
  19218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19219. this._defines.UV1 = true;
  19220. }
  19221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19222. this._defines.UV2 = true;
  19223. }
  19224. }
  19225. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19226. this._defines.VERTEXCOLOR = true;
  19227. if (mesh.hasVertexAlpha) {
  19228. this._defines.VERTEXALPHA = true;
  19229. }
  19230. }
  19231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19232. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19233. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19234. }
  19235. // Instances
  19236. if (useInstances) {
  19237. this._defines.INSTANCES = true;
  19238. }
  19239. }
  19240. // Get correct effect
  19241. if (!this._defines.isEqual(this._cachedDefines)) {
  19242. this._defines.cloneTo(this._cachedDefines);
  19243. scene.resetCachedMaterial();
  19244. // Fallbacks
  19245. var fallbacks = new BABYLON.EffectFallbacks();
  19246. if (this._defines.REFLECTION) {
  19247. fallbacks.addFallback(0, "REFLECTION");
  19248. }
  19249. if (this._defines.SPECULAR) {
  19250. fallbacks.addFallback(0, "SPECULAR");
  19251. }
  19252. if (this._defines.BUMP) {
  19253. fallbacks.addFallback(0, "BUMP");
  19254. }
  19255. if (this._defines.SPECULAROVERALPHA) {
  19256. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19257. }
  19258. if (this._defines.FOG) {
  19259. fallbacks.addFallback(1, "FOG");
  19260. }
  19261. if (this._defines.POINTSIZE) {
  19262. fallbacks.addFallback(0, "POINTSIZE");
  19263. }
  19264. if (this._defines.LOGARITHMICDEPTH) {
  19265. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19266. }
  19267. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19268. if (!this._defines["LIGHT" + lightIndex]) {
  19269. continue;
  19270. }
  19271. if (lightIndex > 0) {
  19272. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19273. }
  19274. if (this._defines["SHADOW" + lightIndex]) {
  19275. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19276. }
  19277. if (this._defines["SHADOWPCF" + lightIndex]) {
  19278. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19279. }
  19280. if (this._defines["SHADOWVSM" + lightIndex]) {
  19281. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19282. }
  19283. }
  19284. if (this._defines.SPECULARTERM) {
  19285. fallbacks.addFallback(0, "SPECULARTERM");
  19286. }
  19287. if (this._defines.DIFFUSEFRESNEL) {
  19288. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19289. }
  19290. if (this._defines.OPACITYFRESNEL) {
  19291. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19292. }
  19293. if (this._defines.REFLECTIONFRESNEL) {
  19294. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19295. }
  19296. if (this._defines.EMISSIVEFRESNEL) {
  19297. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19298. }
  19299. if (this._defines.FRESNEL) {
  19300. fallbacks.addFallback(4, "FRESNEL");
  19301. }
  19302. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19303. fallbacks.addCPUSkinningFallback(0, mesh);
  19304. }
  19305. //Attributes
  19306. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19307. if (this._defines.NORMAL) {
  19308. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19309. }
  19310. if (this._defines.UV1) {
  19311. attribs.push(BABYLON.VertexBuffer.UVKind);
  19312. }
  19313. if (this._defines.UV2) {
  19314. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19315. }
  19316. if (this._defines.VERTEXCOLOR) {
  19317. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19318. }
  19319. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19320. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19321. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19322. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19323. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19324. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19325. }
  19326. }
  19327. if (this._defines.INSTANCES) {
  19328. attribs.push("world0");
  19329. attribs.push("world1");
  19330. attribs.push("world2");
  19331. attribs.push("world3");
  19332. }
  19333. // Legacy browser patch
  19334. var shaderName = "default";
  19335. if (!scene.getEngine().getCaps().standardDerivatives) {
  19336. shaderName = "legacydefault";
  19337. }
  19338. var join = this._defines.toString();
  19339. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19340. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19341. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19342. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19343. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19344. "vFogInfos", "vFogColor", "pointSize",
  19345. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19346. "mBones",
  19347. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19348. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19349. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19350. "logarithmicDepthConstant"
  19351. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19352. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19353. ], join, fallbacks, this.onCompiled, this.onError);
  19354. }
  19355. if (!this._effect.isReady()) {
  19356. return false;
  19357. }
  19358. this._renderId = scene.getRenderId();
  19359. this._wasPreviouslyReady = true;
  19360. if (mesh) {
  19361. if (!mesh._materialDefines) {
  19362. mesh._materialDefines = new StandardMaterialDefines();
  19363. }
  19364. this._defines.cloneTo(mesh._materialDefines);
  19365. }
  19366. return true;
  19367. };
  19368. StandardMaterial.prototype.unbind = function () {
  19369. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19370. this._effect.setTexture("reflection2DSampler", null);
  19371. }
  19372. _super.prototype.unbind.call(this);
  19373. };
  19374. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19375. this._effect.setMatrix("world", world);
  19376. };
  19377. StandardMaterial.prototype.bind = function (world, mesh) {
  19378. var scene = this.getScene();
  19379. // Matrices
  19380. this.bindOnlyWorldMatrix(world);
  19381. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19382. // Bones
  19383. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19384. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19385. }
  19386. if (scene.getCachedMaterial() !== this) {
  19387. if (StandardMaterial.FresnelEnabled) {
  19388. // Fresnel
  19389. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19390. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19391. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19392. }
  19393. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19394. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19395. }
  19396. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19397. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19398. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19399. }
  19400. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19401. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19402. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19403. }
  19404. }
  19405. // Textures
  19406. if (scene.texturesEnabled) {
  19407. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19408. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19409. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19410. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19411. }
  19412. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19413. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19414. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19415. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19416. }
  19417. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19418. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19419. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19420. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19421. }
  19422. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19423. if (this.reflectionTexture.isCube) {
  19424. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19425. }
  19426. else {
  19427. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19428. }
  19429. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19430. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19431. }
  19432. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19433. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19434. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19435. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19436. }
  19437. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19438. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19439. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19440. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19441. }
  19442. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19443. this._effect.setTexture("specularSampler", this.specularTexture);
  19444. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19445. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19446. }
  19447. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19448. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19449. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19450. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19451. }
  19452. }
  19453. // Clip plane
  19454. if (scene.clipPlane) {
  19455. var clipPlane = scene.clipPlane;
  19456. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19457. }
  19458. // Point size
  19459. if (this.pointsCloud) {
  19460. this._effect.setFloat("pointSize", this.pointSize);
  19461. }
  19462. // Colors
  19463. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19464. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19465. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19466. if (this._defines.SPECULARTERM) {
  19467. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19468. }
  19469. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19470. }
  19471. // Diffuse
  19472. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19473. // Lights
  19474. if (scene.lightsEnabled && !this.disableLighting) {
  19475. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19476. }
  19477. // View
  19478. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19479. this._effect.setMatrix("view", scene.getViewMatrix());
  19480. }
  19481. // Fog
  19482. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19483. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19484. this._effect.setColor3("vFogColor", scene.fogColor);
  19485. }
  19486. // Log. depth
  19487. if (this._defines.LOGARITHMICDEPTH) {
  19488. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19489. }
  19490. _super.prototype.bind.call(this, world, mesh);
  19491. };
  19492. StandardMaterial.prototype.getAnimatables = function () {
  19493. var results = [];
  19494. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19495. results.push(this.diffuseTexture);
  19496. }
  19497. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19498. results.push(this.ambientTexture);
  19499. }
  19500. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19501. results.push(this.opacityTexture);
  19502. }
  19503. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19504. results.push(this.reflectionTexture);
  19505. }
  19506. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19507. results.push(this.emissiveTexture);
  19508. }
  19509. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19510. results.push(this.specularTexture);
  19511. }
  19512. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19513. results.push(this.bumpTexture);
  19514. }
  19515. return results;
  19516. };
  19517. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19518. if (this.diffuseTexture) {
  19519. this.diffuseTexture.dispose();
  19520. }
  19521. if (this.ambientTexture) {
  19522. this.ambientTexture.dispose();
  19523. }
  19524. if (this.opacityTexture) {
  19525. this.opacityTexture.dispose();
  19526. }
  19527. if (this.reflectionTexture) {
  19528. this.reflectionTexture.dispose();
  19529. }
  19530. if (this.emissiveTexture) {
  19531. this.emissiveTexture.dispose();
  19532. }
  19533. if (this.specularTexture) {
  19534. this.specularTexture.dispose();
  19535. }
  19536. if (this.bumpTexture) {
  19537. this.bumpTexture.dispose();
  19538. }
  19539. _super.prototype.dispose.call(this, forceDisposeEffect);
  19540. };
  19541. StandardMaterial.prototype.clone = function (name) {
  19542. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19543. // Base material
  19544. this.copyTo(newStandardMaterial);
  19545. // Standard material
  19546. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19547. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19548. }
  19549. if (this.ambientTexture && this.ambientTexture.clone) {
  19550. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19551. }
  19552. if (this.opacityTexture && this.opacityTexture.clone) {
  19553. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19554. }
  19555. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19556. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19557. }
  19558. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19559. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19560. }
  19561. if (this.specularTexture && this.specularTexture.clone) {
  19562. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19563. }
  19564. if (this.bumpTexture && this.bumpTexture.clone) {
  19565. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19566. }
  19567. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19568. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19569. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19570. }
  19571. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19572. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19573. newStandardMaterial.specularColor = this.specularColor.clone();
  19574. newStandardMaterial.specularPower = this.specularPower;
  19575. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19576. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19577. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19578. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19579. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19580. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19581. newStandardMaterial.roughness = this.roughness;
  19582. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19583. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19584. }
  19585. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19586. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19587. }
  19588. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19589. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19590. }
  19591. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19592. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19593. }
  19594. return newStandardMaterial;
  19595. };
  19596. StandardMaterial.prototype.serialize = function () {
  19597. var serializationObject = _super.prototype.serialize.call(this);
  19598. serializationObject.ambient = this.ambientColor.asArray();
  19599. serializationObject.diffuse = this.diffuseColor.asArray();
  19600. serializationObject.specular = this.specularColor.asArray();
  19601. serializationObject.specularPower = this.specularPower;
  19602. serializationObject.emissive = this.emissiveColor.asArray();
  19603. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19604. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19605. if (this.diffuseTexture) {
  19606. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19607. }
  19608. if (this.diffuseFresnelParameters) {
  19609. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19610. }
  19611. if (this.ambientTexture) {
  19612. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19613. }
  19614. if (this.opacityTexture) {
  19615. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19616. }
  19617. if (this.opacityFresnelParameters) {
  19618. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19619. }
  19620. if (this.reflectionTexture) {
  19621. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19622. }
  19623. if (this.reflectionFresnelParameters) {
  19624. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19625. }
  19626. if (this.emissiveTexture) {
  19627. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19628. }
  19629. if (this.lightmapTexture) {
  19630. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19631. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19632. }
  19633. if (this.emissiveFresnelParameters) {
  19634. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19635. }
  19636. if (this.specularTexture) {
  19637. serializationObject.specularTexture = this.specularTexture.serialize();
  19638. }
  19639. if (this.bumpTexture) {
  19640. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19641. }
  19642. return serializationObject;
  19643. };
  19644. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19645. var material = new StandardMaterial(source.name, scene);
  19646. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19647. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19648. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19649. material.specularPower = source.specularPower;
  19650. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19651. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19652. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19653. material.alpha = source.alpha;
  19654. material.id = source.id;
  19655. if (source.disableDepthWrite) {
  19656. material.disableDepthWrite = source.disableDepthWrite;
  19657. }
  19658. BABYLON.Tags.AddTagsTo(material, source.tags);
  19659. material.backFaceCulling = source.backFaceCulling;
  19660. material.wireframe = source.wireframe;
  19661. if (source.diffuseTexture) {
  19662. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19663. }
  19664. if (source.diffuseFresnelParameters) {
  19665. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19666. }
  19667. if (source.ambientTexture) {
  19668. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19669. }
  19670. if (source.opacityTexture) {
  19671. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19672. }
  19673. if (source.opacityFresnelParameters) {
  19674. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19675. }
  19676. if (source.reflectionTexture) {
  19677. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19678. }
  19679. if (source.reflectionFresnelParameters) {
  19680. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19681. }
  19682. if (source.emissiveTexture) {
  19683. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19684. }
  19685. if (source.lightmapTexture) {
  19686. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19687. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19688. }
  19689. if (source.emissiveFresnelParameters) {
  19690. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19691. }
  19692. if (source.specularTexture) {
  19693. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19694. }
  19695. if (source.bumpTexture) {
  19696. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19697. }
  19698. if (source.checkReadyOnlyOnce) {
  19699. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19700. }
  19701. return material;
  19702. };
  19703. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19704. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19705. // Statics
  19706. // Flags used to enable or disable a type of texture for all Standard Materials
  19707. StandardMaterial.DiffuseTextureEnabled = true;
  19708. StandardMaterial.AmbientTextureEnabled = true;
  19709. StandardMaterial.OpacityTextureEnabled = true;
  19710. StandardMaterial.ReflectionTextureEnabled = true;
  19711. StandardMaterial.EmissiveTextureEnabled = true;
  19712. StandardMaterial.SpecularTextureEnabled = true;
  19713. StandardMaterial.BumpTextureEnabled = true;
  19714. StandardMaterial.FresnelEnabled = true;
  19715. StandardMaterial.LightmapEnabled = true;
  19716. return StandardMaterial;
  19717. })(BABYLON.Material);
  19718. BABYLON.StandardMaterial = StandardMaterial;
  19719. })(BABYLON || (BABYLON = {}));
  19720. var BABYLON;
  19721. (function (BABYLON) {
  19722. var MultiMaterial = (function (_super) {
  19723. __extends(MultiMaterial, _super);
  19724. function MultiMaterial(name, scene) {
  19725. _super.call(this, name, scene, true);
  19726. this.subMaterials = new Array();
  19727. scene.multiMaterials.push(this);
  19728. }
  19729. // Properties
  19730. MultiMaterial.prototype.getSubMaterial = function (index) {
  19731. if (index < 0 || index >= this.subMaterials.length) {
  19732. return this.getScene().defaultMaterial;
  19733. }
  19734. return this.subMaterials[index];
  19735. };
  19736. // Methods
  19737. MultiMaterial.prototype.isReady = function (mesh) {
  19738. for (var index = 0; index < this.subMaterials.length; index++) {
  19739. var subMaterial = this.subMaterials[index];
  19740. if (subMaterial) {
  19741. if (!this.subMaterials[index].isReady(mesh)) {
  19742. return false;
  19743. }
  19744. }
  19745. }
  19746. return true;
  19747. };
  19748. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19749. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19750. for (var index = 0; index < this.subMaterials.length; index++) {
  19751. var subMaterial = null;
  19752. if (cloneChildren) {
  19753. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19754. }
  19755. else {
  19756. subMaterial = this.subMaterials[index];
  19757. }
  19758. newMultiMaterial.subMaterials.push(subMaterial);
  19759. }
  19760. return newMultiMaterial;
  19761. };
  19762. MultiMaterial.prototype.serialize = function () {
  19763. var serializationObject = {};
  19764. serializationObject.name = this.name;
  19765. serializationObject.id = this.id;
  19766. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19767. serializationObject.materials = [];
  19768. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19769. var subMat = this.subMaterials[matIndex];
  19770. if (subMat) {
  19771. serializationObject.materials.push(subMat.id);
  19772. }
  19773. else {
  19774. serializationObject.materials.push(null);
  19775. }
  19776. }
  19777. return serializationObject;
  19778. };
  19779. return MultiMaterial;
  19780. })(BABYLON.Material);
  19781. BABYLON.MultiMaterial = MultiMaterial;
  19782. })(BABYLON || (BABYLON = {}));
  19783. var BABYLON;
  19784. (function (BABYLON) {
  19785. var SceneLoader = (function () {
  19786. function SceneLoader() {
  19787. }
  19788. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19789. get: function () {
  19790. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19791. },
  19792. set: function (value) {
  19793. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19799. get: function () {
  19800. return SceneLoader._ShowLoadingScreen;
  19801. },
  19802. set: function (value) {
  19803. SceneLoader._ShowLoadingScreen = value;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19809. var dotPosition = sceneFilename.lastIndexOf(".");
  19810. var queryStringPosition = sceneFilename.indexOf("?");
  19811. if (queryStringPosition === -1) {
  19812. queryStringPosition = sceneFilename.length;
  19813. }
  19814. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19815. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19816. var plugin = this._registeredPlugins[index];
  19817. if (plugin.extensions.indexOf(extension) !== -1) {
  19818. return plugin;
  19819. }
  19820. }
  19821. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19822. };
  19823. // Public functions
  19824. SceneLoader.RegisterPlugin = function (plugin) {
  19825. plugin.extensions = plugin.extensions.toLowerCase();
  19826. SceneLoader._registeredPlugins.push(plugin);
  19827. };
  19828. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19829. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19830. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19831. return;
  19832. }
  19833. var loadingToken = {};
  19834. scene._addPendingData(loadingToken);
  19835. var manifestChecked = function (success) {
  19836. scene.database = database;
  19837. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19838. var importMeshFromData = function (data) {
  19839. var meshes = [];
  19840. var particleSystems = [];
  19841. var skeletons = [];
  19842. try {
  19843. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19844. if (onerror) {
  19845. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19846. }
  19847. scene._removePendingData(loadingToken);
  19848. return;
  19849. }
  19850. }
  19851. catch (e) {
  19852. if (onerror) {
  19853. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19854. }
  19855. scene._removePendingData(loadingToken);
  19856. return;
  19857. }
  19858. if (onsuccess) {
  19859. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19860. onsuccess(meshes, particleSystems, skeletons);
  19861. scene._removePendingData(loadingToken);
  19862. }
  19863. };
  19864. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19865. // Direct load
  19866. importMeshFromData(sceneFilename.substr(5));
  19867. return;
  19868. }
  19869. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19870. importMeshFromData(data);
  19871. }, progressCallBack, database);
  19872. };
  19873. if (scene.getEngine().enableOfflineSupport) {
  19874. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19875. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19876. }
  19877. else {
  19878. manifestChecked(true);
  19879. }
  19880. };
  19881. /**
  19882. * Load a scene
  19883. * @param rootUrl a string that defines the root url for scene and resources
  19884. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19885. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19886. */
  19887. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19888. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19889. };
  19890. /**
  19891. * Append a scene
  19892. * @param rootUrl a string that defines the root url for scene and resources
  19893. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19894. * @param scene is the instance of BABYLON.Scene to append to
  19895. */
  19896. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19897. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19898. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19899. return;
  19900. }
  19901. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19902. var database;
  19903. var loadingToken = {};
  19904. scene._addPendingData(loadingToken);
  19905. if (SceneLoader.ShowLoadingScreen) {
  19906. scene.getEngine().displayLoadingUI();
  19907. }
  19908. var loadSceneFromData = function (data) {
  19909. scene.database = database;
  19910. if (!plugin.load(scene, data, rootUrl)) {
  19911. if (onerror) {
  19912. onerror(scene);
  19913. }
  19914. scene._removePendingData(loadingToken);
  19915. scene.getEngine().hideLoadingUI();
  19916. return;
  19917. }
  19918. if (onsuccess) {
  19919. onsuccess(scene);
  19920. }
  19921. scene._removePendingData(loadingToken);
  19922. if (SceneLoader.ShowLoadingScreen) {
  19923. scene.executeWhenReady(function () {
  19924. scene.getEngine().hideLoadingUI();
  19925. });
  19926. }
  19927. };
  19928. var manifestChecked = function (success) {
  19929. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19930. };
  19931. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19932. // Direct load
  19933. loadSceneFromData(sceneFilename.substr(5));
  19934. return;
  19935. }
  19936. if (rootUrl.indexOf("file:") === -1) {
  19937. if (scene.getEngine().enableOfflineSupport) {
  19938. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19939. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19940. }
  19941. else {
  19942. manifestChecked(true);
  19943. }
  19944. }
  19945. else {
  19946. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19947. }
  19948. };
  19949. // Flags
  19950. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19951. SceneLoader._ShowLoadingScreen = true;
  19952. // Members
  19953. SceneLoader._registeredPlugins = new Array();
  19954. return SceneLoader;
  19955. })();
  19956. BABYLON.SceneLoader = SceneLoader;
  19957. ;
  19958. })(BABYLON || (BABYLON = {}));
  19959. var BABYLON;
  19960. (function (BABYLON) {
  19961. var Internals;
  19962. (function (Internals) {
  19963. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19964. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  19965. var parsedMaterial = parsedData.materials[index];
  19966. if (parsedMaterial.id === id) {
  19967. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  19968. }
  19969. }
  19970. return null;
  19971. };
  19972. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19973. names = (names instanceof Array) ? names : [names];
  19974. for (var i in names) {
  19975. if (mesh.name === names[i]) {
  19976. hierarchyIds.push(mesh.id);
  19977. return true;
  19978. }
  19979. }
  19980. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19981. hierarchyIds.push(mesh.id);
  19982. return true;
  19983. }
  19984. return false;
  19985. };
  19986. BABYLON.SceneLoader.RegisterPlugin({
  19987. extensions: ".babylon",
  19988. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19989. var parsedData = JSON.parse(data);
  19990. var loadedSkeletonsIds = [];
  19991. var loadedMaterialsIds = [];
  19992. var hierarchyIds = [];
  19993. var index;
  19994. var cache;
  19995. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  19996. var parsedMesh = parsedData.meshes[index];
  19997. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19998. if (meshesNames instanceof Array) {
  19999. // Remove found mesh name from list.
  20000. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20001. }
  20002. //Geometry?
  20003. if (parsedMesh.geometryId) {
  20004. //does the file contain geometries?
  20005. if (parsedData.geometries) {
  20006. //find the correct geometry and add it to the scene
  20007. var found = false;
  20008. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20009. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20010. return;
  20011. }
  20012. else {
  20013. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20014. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20015. switch (geometryType) {
  20016. case "boxes":
  20017. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20018. break;
  20019. case "spheres":
  20020. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20021. break;
  20022. case "cylinders":
  20023. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20024. break;
  20025. case "toruses":
  20026. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20027. break;
  20028. case "grounds":
  20029. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20030. break;
  20031. case "planes":
  20032. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20033. break;
  20034. case "torusKnots":
  20035. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20036. break;
  20037. case "vertexData":
  20038. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20039. break;
  20040. }
  20041. found = true;
  20042. }
  20043. });
  20044. }
  20045. });
  20046. if (!found) {
  20047. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20048. }
  20049. }
  20050. }
  20051. // Material ?
  20052. if (parsedMesh.materialId) {
  20053. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20054. if (!materialFound && parsedData.multiMaterials) {
  20055. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20056. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20057. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20058. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20059. var subMatId = parsedMultiMaterial.materials[matIndex];
  20060. loadedMaterialsIds.push(subMatId);
  20061. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20062. }
  20063. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20064. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20065. materialFound = true;
  20066. break;
  20067. }
  20068. }
  20069. }
  20070. if (!materialFound) {
  20071. loadedMaterialsIds.push(parsedMesh.materialId);
  20072. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20073. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20074. }
  20075. }
  20076. }
  20077. // Skeleton ?
  20078. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20079. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20080. if (!skeletonAlreadyLoaded) {
  20081. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20082. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20083. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20084. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20085. loadedSkeletonsIds.push(parsedSkeleton.id);
  20086. }
  20087. }
  20088. }
  20089. }
  20090. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20091. meshes.push(mesh);
  20092. }
  20093. }
  20094. // Connecting parents
  20095. var currentMesh;
  20096. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20097. currentMesh = scene.meshes[index];
  20098. if (currentMesh._waitingParentId) {
  20099. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20100. currentMesh._waitingParentId = undefined;
  20101. }
  20102. }
  20103. // freeze world matrix application
  20104. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20105. currentMesh = scene.meshes[index];
  20106. if (currentMesh._waitingFreezeWorldMatrix) {
  20107. currentMesh.freezeWorldMatrix();
  20108. currentMesh._waitingFreezeWorldMatrix = undefined;
  20109. }
  20110. }
  20111. // Particles
  20112. if (parsedData.particleSystems) {
  20113. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20114. var parsedParticleSystem = parsedData.particleSystems[index];
  20115. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20116. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20117. }
  20118. }
  20119. }
  20120. return true;
  20121. },
  20122. load: function (scene, data, rootUrl) {
  20123. var parsedData = JSON.parse(data);
  20124. // Scene
  20125. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20126. scene.autoClear = parsedData.autoClear;
  20127. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20128. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20129. if (parsedData.gravity) {
  20130. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20131. }
  20132. // Fog
  20133. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20134. scene.fogMode = parsedData.fogMode;
  20135. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20136. scene.fogStart = parsedData.fogStart;
  20137. scene.fogEnd = parsedData.fogEnd;
  20138. scene.fogDensity = parsedData.fogDensity;
  20139. }
  20140. //Physics
  20141. if (parsedData.physicsEnabled) {
  20142. var physicsPlugin;
  20143. if (parsedData.physicsEngine === "cannon") {
  20144. physicsPlugin = new BABYLON.CannonJSPlugin();
  20145. }
  20146. else if (parsedData.physicsEngine === "oimo") {
  20147. physicsPlugin = new BABYLON.OimoJSPlugin();
  20148. }
  20149. //else - default engine, which is currently oimo
  20150. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20151. scene.enablePhysics(physicsGravity, physicsPlugin);
  20152. }
  20153. //collisions, if defined. otherwise, default is true
  20154. if (parsedData.collisionsEnabled != undefined) {
  20155. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20156. }
  20157. scene.workerCollisions = !!parsedData.workerCollisions;
  20158. var index;
  20159. var cache;
  20160. // Lights
  20161. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20162. var parsedLight = parsedData.lights[index];
  20163. BABYLON.Light.Parse(parsedLight, scene);
  20164. }
  20165. // Materials
  20166. if (parsedData.materials) {
  20167. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20168. var parsedMaterial = parsedData.materials[index];
  20169. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20170. }
  20171. }
  20172. if (parsedData.multiMaterials) {
  20173. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20174. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20175. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20176. }
  20177. }
  20178. // Skeletons
  20179. if (parsedData.skeletons) {
  20180. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20181. var parsedSkeleton = parsedData.skeletons[index];
  20182. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20183. }
  20184. }
  20185. // Geometries
  20186. var geometries = parsedData.geometries;
  20187. if (geometries) {
  20188. // Boxes
  20189. var boxes = geometries.boxes;
  20190. if (boxes) {
  20191. for (index = 0, cache = boxes.length; index < cache; index++) {
  20192. var parsedBox = boxes[index];
  20193. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20194. }
  20195. }
  20196. // Spheres
  20197. var spheres = geometries.spheres;
  20198. if (spheres) {
  20199. for (index = 0, cache = spheres.length; index < cache; index++) {
  20200. var parsedSphere = spheres[index];
  20201. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20202. }
  20203. }
  20204. // Cylinders
  20205. var cylinders = geometries.cylinders;
  20206. if (cylinders) {
  20207. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20208. var parsedCylinder = cylinders[index];
  20209. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20210. }
  20211. }
  20212. // Toruses
  20213. var toruses = geometries.toruses;
  20214. if (toruses) {
  20215. for (index = 0, cache = toruses.length; index < cache; index++) {
  20216. var parsedTorus = toruses[index];
  20217. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20218. }
  20219. }
  20220. // Grounds
  20221. var grounds = geometries.grounds;
  20222. if (grounds) {
  20223. for (index = 0, cache = grounds.length; index < cache; index++) {
  20224. var parsedGround = grounds[index];
  20225. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20226. }
  20227. }
  20228. // Planes
  20229. var planes = geometries.planes;
  20230. if (planes) {
  20231. for (index = 0, cache = planes.length; index < cache; index++) {
  20232. var parsedPlane = planes[index];
  20233. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20234. }
  20235. }
  20236. // TorusKnots
  20237. var torusKnots = geometries.torusKnots;
  20238. if (torusKnots) {
  20239. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20240. var parsedTorusKnot = torusKnots[index];
  20241. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20242. }
  20243. }
  20244. // VertexData
  20245. var vertexData = geometries.vertexData;
  20246. if (vertexData) {
  20247. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20248. var parsedVertexData = vertexData[index];
  20249. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20250. }
  20251. }
  20252. }
  20253. // Meshes
  20254. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20255. var parsedMesh = parsedData.meshes[index];
  20256. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20257. }
  20258. // Cameras
  20259. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20260. var parsedCamera = parsedData.cameras[index];
  20261. BABYLON.Camera.Parse(parsedCamera, scene);
  20262. }
  20263. if (parsedData.activeCameraID) {
  20264. scene.setActiveCameraByID(parsedData.activeCameraID);
  20265. }
  20266. // Browsing all the graph to connect the dots
  20267. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20268. var camera = scene.cameras[index];
  20269. if (camera._waitingParentId) {
  20270. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20271. camera._waitingParentId = undefined;
  20272. }
  20273. }
  20274. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20275. var light = scene.lights[index];
  20276. if (light._waitingParentId) {
  20277. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20278. light._waitingParentId = undefined;
  20279. }
  20280. }
  20281. // Sounds
  20282. if (BABYLON.AudioEngine && parsedData.sounds) {
  20283. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20284. var parsedSound = parsedData.sounds[index];
  20285. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20286. BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20287. }
  20288. else {
  20289. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20290. }
  20291. }
  20292. }
  20293. // Connect parents & children and parse actions
  20294. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20295. var mesh = scene.meshes[index];
  20296. if (mesh._waitingParentId) {
  20297. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20298. mesh._waitingParentId = undefined;
  20299. }
  20300. if (mesh._waitingActions) {
  20301. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20302. mesh._waitingActions = undefined;
  20303. }
  20304. }
  20305. // freeze world matrix application
  20306. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20307. var currentMesh = scene.meshes[index];
  20308. if (currentMesh._waitingFreezeWorldMatrix) {
  20309. currentMesh.freezeWorldMatrix();
  20310. currentMesh._waitingFreezeWorldMatrix = undefined;
  20311. }
  20312. }
  20313. // Particles Systems
  20314. if (parsedData.particleSystems) {
  20315. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20316. var parsedParticleSystem = parsedData.particleSystems[index];
  20317. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20318. }
  20319. }
  20320. // Lens flares
  20321. if (parsedData.lensFlareSystems) {
  20322. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20323. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20324. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20325. }
  20326. }
  20327. // Shadows
  20328. if (parsedData.shadowGenerators) {
  20329. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20330. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20331. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20332. }
  20333. }
  20334. // Actions (scene)
  20335. if (parsedData.actions) {
  20336. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20337. }
  20338. // Finish
  20339. return true;
  20340. }
  20341. });
  20342. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20343. })(BABYLON || (BABYLON = {}));
  20344. var BABYLON;
  20345. (function (BABYLON) {
  20346. var SpriteManager = (function () {
  20347. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20349. this.name = name;
  20350. this.cellSize = cellSize;
  20351. this.sprites = new Array();
  20352. this.renderingGroupId = 0;
  20353. this.layerMask = 0x0FFFFFFF;
  20354. this.fogEnabled = true;
  20355. this.isPickable = false;
  20356. this._vertexDeclaration = [4, 4, 4, 4];
  20357. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20358. this._capacity = capacity;
  20359. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20360. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20361. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20362. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20363. this._scene = scene;
  20364. this._scene.spriteManagers.push(this);
  20365. // VBO
  20366. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20367. var indices = [];
  20368. var index = 0;
  20369. for (var count = 0; count < capacity; count++) {
  20370. indices.push(index);
  20371. indices.push(index + 1);
  20372. indices.push(index + 2);
  20373. indices.push(index);
  20374. indices.push(index + 2);
  20375. indices.push(index + 3);
  20376. index += 4;
  20377. }
  20378. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20379. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20380. // Effects
  20381. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20382. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20383. }
  20384. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20385. var arrayOffset = index * 16;
  20386. if (offsetX === 0)
  20387. offsetX = this._epsilon;
  20388. else if (offsetX === 1)
  20389. offsetX = 1 - this._epsilon;
  20390. if (offsetY === 0)
  20391. offsetY = this._epsilon;
  20392. else if (offsetY === 1)
  20393. offsetY = 1 - this._epsilon;
  20394. this._vertices[arrayOffset] = sprite.position.x;
  20395. this._vertices[arrayOffset + 1] = sprite.position.y;
  20396. this._vertices[arrayOffset + 2] = sprite.position.z;
  20397. this._vertices[arrayOffset + 3] = sprite.angle;
  20398. this._vertices[arrayOffset + 4] = sprite.width;
  20399. this._vertices[arrayOffset + 5] = sprite.height;
  20400. this._vertices[arrayOffset + 6] = offsetX;
  20401. this._vertices[arrayOffset + 7] = offsetY;
  20402. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20403. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20404. var offset = (sprite.cellIndex / rowSize) >> 0;
  20405. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20406. this._vertices[arrayOffset + 11] = offset;
  20407. // Color
  20408. this._vertices[arrayOffset + 12] = sprite.color.r;
  20409. this._vertices[arrayOffset + 13] = sprite.color.g;
  20410. this._vertices[arrayOffset + 14] = sprite.color.b;
  20411. this._vertices[arrayOffset + 15] = sprite.color.a;
  20412. };
  20413. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20414. var count = Math.min(this._capacity, this.sprites.length);
  20415. var min = BABYLON.Vector3.Zero();
  20416. var max = BABYLON.Vector3.Zero();
  20417. var distance = Number.MAX_VALUE;
  20418. var currentSprite;
  20419. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20420. var cameraView = camera.getViewMatrix();
  20421. for (var index = 0; index < count; index++) {
  20422. var sprite = this.sprites[index];
  20423. if (!sprite) {
  20424. continue;
  20425. }
  20426. if (predicate) {
  20427. if (!predicate(sprite)) {
  20428. continue;
  20429. }
  20430. }
  20431. else if (!sprite.isPickable) {
  20432. continue;
  20433. }
  20434. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20435. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20436. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20437. if (ray.intersectsBoxMinMax(min, max)) {
  20438. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20439. if (distance > currentDistance) {
  20440. distance = currentDistance;
  20441. currentSprite = sprite;
  20442. if (fastCheck) {
  20443. break;
  20444. }
  20445. }
  20446. }
  20447. }
  20448. if (currentSprite) {
  20449. var result = new BABYLON.PickingInfo();
  20450. result.hit = true;
  20451. result.pickedSprite = currentSprite;
  20452. result.distance = distance;
  20453. return result;
  20454. }
  20455. return null;
  20456. };
  20457. SpriteManager.prototype.render = function () {
  20458. // Check
  20459. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20460. return;
  20461. var engine = this._scene.getEngine();
  20462. var baseSize = this._spriteTexture.getBaseSize();
  20463. // Sprites
  20464. var deltaTime = engine.getDeltaTime();
  20465. var max = Math.min(this._capacity, this.sprites.length);
  20466. var rowSize = baseSize.width / this.cellSize;
  20467. var offset = 0;
  20468. for (var index = 0; index < max; index++) {
  20469. var sprite = this.sprites[index];
  20470. if (!sprite) {
  20471. continue;
  20472. }
  20473. sprite._animate(deltaTime);
  20474. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20475. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20476. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20477. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20478. }
  20479. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20480. // Render
  20481. var effect = this._effectBase;
  20482. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20483. effect = this._effectFog;
  20484. }
  20485. engine.enableEffect(effect);
  20486. var viewMatrix = this._scene.getViewMatrix();
  20487. effect.setTexture("diffuseSampler", this._spriteTexture);
  20488. effect.setMatrix("view", viewMatrix);
  20489. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20490. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20491. // Fog
  20492. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20493. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20494. effect.setColor3("vFogColor", this._scene.fogColor);
  20495. }
  20496. // VBOs
  20497. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20498. // Draw order
  20499. engine.setDepthFunctionToLessOrEqual();
  20500. effect.setBool("alphaTest", true);
  20501. engine.setColorWrite(false);
  20502. engine.draw(true, 0, max * 6);
  20503. engine.setColorWrite(true);
  20504. effect.setBool("alphaTest", false);
  20505. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20506. engine.draw(true, 0, max * 6);
  20507. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20508. };
  20509. SpriteManager.prototype.dispose = function () {
  20510. if (this._vertexBuffer) {
  20511. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20512. this._vertexBuffer = null;
  20513. }
  20514. if (this._indexBuffer) {
  20515. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20516. this._indexBuffer = null;
  20517. }
  20518. if (this._spriteTexture) {
  20519. this._spriteTexture.dispose();
  20520. this._spriteTexture = null;
  20521. }
  20522. // Remove from scene
  20523. var index = this._scene.spriteManagers.indexOf(this);
  20524. this._scene.spriteManagers.splice(index, 1);
  20525. // Callback
  20526. if (this.onDispose) {
  20527. this.onDispose();
  20528. }
  20529. };
  20530. return SpriteManager;
  20531. })();
  20532. BABYLON.SpriteManager = SpriteManager;
  20533. })(BABYLON || (BABYLON = {}));
  20534. var BABYLON;
  20535. (function (BABYLON) {
  20536. var Sprite = (function () {
  20537. function Sprite(name, manager) {
  20538. this.name = name;
  20539. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20540. this.width = 1.0;
  20541. this.height = 1.0;
  20542. this.angle = 0;
  20543. this.cellIndex = 0;
  20544. this.invertU = 0;
  20545. this.invertV = 0;
  20546. this.animations = new Array();
  20547. this.isPickable = false;
  20548. this._animationStarted = false;
  20549. this._loopAnimation = false;
  20550. this._fromIndex = 0;
  20551. this._toIndex = 0;
  20552. this._delay = 0;
  20553. this._direction = 1;
  20554. this._frameCount = 0;
  20555. this._time = 0;
  20556. this._manager = manager;
  20557. this._manager.sprites.push(this);
  20558. this.position = BABYLON.Vector3.Zero();
  20559. }
  20560. Object.defineProperty(Sprite.prototype, "size", {
  20561. get: function () {
  20562. return this.width;
  20563. },
  20564. set: function (value) {
  20565. this.width = value;
  20566. this.height = value;
  20567. },
  20568. enumerable: true,
  20569. configurable: true
  20570. });
  20571. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20572. this._fromIndex = from;
  20573. this._toIndex = to;
  20574. this._loopAnimation = loop;
  20575. this._delay = delay;
  20576. this._animationStarted = true;
  20577. this._direction = from < to ? 1 : -1;
  20578. this.cellIndex = from;
  20579. this._time = 0;
  20580. };
  20581. Sprite.prototype.stopAnimation = function () {
  20582. this._animationStarted = false;
  20583. };
  20584. Sprite.prototype._animate = function (deltaTime) {
  20585. if (!this._animationStarted)
  20586. return;
  20587. this._time += deltaTime;
  20588. if (this._time > this._delay) {
  20589. this._time = this._time % this._delay;
  20590. this.cellIndex += this._direction;
  20591. if (this.cellIndex == this._toIndex) {
  20592. if (this._loopAnimation) {
  20593. this.cellIndex = this._fromIndex;
  20594. }
  20595. else {
  20596. this._animationStarted = false;
  20597. if (this.disposeWhenFinishedAnimating) {
  20598. this.dispose();
  20599. }
  20600. }
  20601. }
  20602. }
  20603. };
  20604. Sprite.prototype.dispose = function () {
  20605. for (var i = 0; i < this._manager.sprites.length; i++) {
  20606. if (this._manager.sprites[i] == this) {
  20607. this._manager.sprites.splice(i, 1);
  20608. }
  20609. }
  20610. };
  20611. return Sprite;
  20612. })();
  20613. BABYLON.Sprite = Sprite;
  20614. })(BABYLON || (BABYLON = {}));
  20615. var BABYLON;
  20616. (function (BABYLON) {
  20617. var Layer = (function () {
  20618. function Layer(name, imgUrl, scene, isBackground, color) {
  20619. this.name = name;
  20620. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20621. this._vertexDeclaration = [2];
  20622. this._vertexStrideSize = 2 * 4;
  20623. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20624. this.isBackground = isBackground === undefined ? true : isBackground;
  20625. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20626. this._scene = scene;
  20627. this._scene.layers.push(this);
  20628. // VBO
  20629. var vertices = [];
  20630. vertices.push(1, 1);
  20631. vertices.push(-1, 1);
  20632. vertices.push(-1, -1);
  20633. vertices.push(1, -1);
  20634. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20635. // Indices
  20636. var indices = [];
  20637. indices.push(0);
  20638. indices.push(1);
  20639. indices.push(2);
  20640. indices.push(0);
  20641. indices.push(2);
  20642. indices.push(3);
  20643. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20644. // Effects
  20645. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20646. }
  20647. Layer.prototype.render = function () {
  20648. // Check
  20649. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20650. return;
  20651. var engine = this._scene.getEngine();
  20652. // Render
  20653. engine.enableEffect(this._effect);
  20654. engine.setState(false);
  20655. // Texture
  20656. this._effect.setTexture("textureSampler", this.texture);
  20657. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20658. // Color
  20659. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20660. // VBOs
  20661. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20662. // Draw order
  20663. engine.setAlphaMode(this.alphaBlendingMode);
  20664. engine.draw(true, 0, 6);
  20665. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20666. };
  20667. Layer.prototype.dispose = function () {
  20668. if (this._vertexBuffer) {
  20669. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20670. this._vertexBuffer = null;
  20671. }
  20672. if (this._indexBuffer) {
  20673. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20674. this._indexBuffer = null;
  20675. }
  20676. if (this.texture) {
  20677. this.texture.dispose();
  20678. this.texture = null;
  20679. }
  20680. // Remove from scene
  20681. var index = this._scene.layers.indexOf(this);
  20682. this._scene.layers.splice(index, 1);
  20683. // Callback
  20684. if (this.onDispose) {
  20685. this.onDispose();
  20686. }
  20687. };
  20688. return Layer;
  20689. })();
  20690. BABYLON.Layer = Layer;
  20691. })(BABYLON || (BABYLON = {}));
  20692. var BABYLON;
  20693. (function (BABYLON) {
  20694. var Particle = (function () {
  20695. function Particle() {
  20696. this.position = BABYLON.Vector3.Zero();
  20697. this.direction = BABYLON.Vector3.Zero();
  20698. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20699. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20700. this.lifeTime = 1.0;
  20701. this.age = 0;
  20702. this.size = 0;
  20703. this.angle = 0;
  20704. this.angularSpeed = 0;
  20705. }
  20706. Particle.prototype.copyTo = function (other) {
  20707. other.position.copyFrom(this.position);
  20708. other.direction.copyFrom(this.direction);
  20709. other.color.copyFrom(this.color);
  20710. other.colorStep.copyFrom(this.colorStep);
  20711. other.lifeTime = this.lifeTime;
  20712. other.age = this.age;
  20713. other.size = this.size;
  20714. other.angle = this.angle;
  20715. other.angularSpeed = this.angularSpeed;
  20716. };
  20717. return Particle;
  20718. })();
  20719. BABYLON.Particle = Particle;
  20720. })(BABYLON || (BABYLON = {}));
  20721. var BABYLON;
  20722. (function (BABYLON) {
  20723. var randomNumber = function (min, max) {
  20724. if (min === max) {
  20725. return (min);
  20726. }
  20727. var random = Math.random();
  20728. return ((random * (max - min)) + min);
  20729. };
  20730. var ParticleSystem = (function () {
  20731. function ParticleSystem(name, capacity, scene, customEffect) {
  20732. var _this = this;
  20733. this.name = name;
  20734. this.renderingGroupId = 0;
  20735. this.emitter = null;
  20736. this.emitRate = 10;
  20737. this.manualEmitCount = -1;
  20738. this.updateSpeed = 0.01;
  20739. this.targetStopDuration = 0;
  20740. this.disposeOnStop = false;
  20741. this.minEmitPower = 1;
  20742. this.maxEmitPower = 1;
  20743. this.minLifeTime = 1;
  20744. this.maxLifeTime = 1;
  20745. this.minSize = 1;
  20746. this.maxSize = 1;
  20747. this.minAngularSpeed = 0;
  20748. this.maxAngularSpeed = 0;
  20749. this.layerMask = 0x0FFFFFFF;
  20750. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20751. this.forceDepthWrite = false;
  20752. this.gravity = BABYLON.Vector3.Zero();
  20753. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20754. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20755. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20756. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20757. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20758. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20759. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20760. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20761. this.particles = new Array();
  20762. this._vertexDeclaration = [3, 4, 4];
  20763. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20764. this._stockParticles = new Array();
  20765. this._newPartsExcess = 0;
  20766. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20767. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20768. this._scaledDirection = BABYLON.Vector3.Zero();
  20769. this._scaledGravity = BABYLON.Vector3.Zero();
  20770. this._currentRenderId = -1;
  20771. this._started = false;
  20772. this._stopped = false;
  20773. this._actualFrame = 0;
  20774. this.id = name;
  20775. this._capacity = capacity;
  20776. this._scene = scene;
  20777. this._customEffect = customEffect;
  20778. scene.particleSystems.push(this);
  20779. // VBO
  20780. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20781. var indices = [];
  20782. var index = 0;
  20783. for (var count = 0; count < capacity; count++) {
  20784. indices.push(index);
  20785. indices.push(index + 1);
  20786. indices.push(index + 2);
  20787. indices.push(index);
  20788. indices.push(index + 2);
  20789. indices.push(index + 3);
  20790. index += 4;
  20791. }
  20792. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20793. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20794. // Default behaviors
  20795. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20796. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20797. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20798. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20799. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20800. };
  20801. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20802. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20803. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20804. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20806. };
  20807. this.updateFunction = function (particles) {
  20808. for (var index = 0; index < particles.length; index++) {
  20809. var particle = particles[index];
  20810. particle.age += _this._scaledUpdateSpeed;
  20811. if (particle.age >= particle.lifeTime) {
  20812. _this.recycleParticle(particle);
  20813. index--;
  20814. continue;
  20815. }
  20816. else {
  20817. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20818. particle.color.addInPlace(_this._scaledColorStep);
  20819. if (particle.color.a < 0)
  20820. particle.color.a = 0;
  20821. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20822. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20823. particle.position.addInPlace(_this._scaledDirection);
  20824. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20825. particle.direction.addInPlace(_this._scaledGravity);
  20826. }
  20827. }
  20828. };
  20829. }
  20830. ParticleSystem.prototype.recycleParticle = function (particle) {
  20831. var lastParticle = this.particles.pop();
  20832. if (lastParticle !== particle) {
  20833. lastParticle.copyTo(particle);
  20834. this._stockParticles.push(lastParticle);
  20835. }
  20836. };
  20837. ParticleSystem.prototype.getCapacity = function () {
  20838. return this._capacity;
  20839. };
  20840. ParticleSystem.prototype.isAlive = function () {
  20841. return this._alive;
  20842. };
  20843. ParticleSystem.prototype.isStarted = function () {
  20844. return this._started;
  20845. };
  20846. ParticleSystem.prototype.start = function () {
  20847. this._started = true;
  20848. this._stopped = false;
  20849. this._actualFrame = 0;
  20850. };
  20851. ParticleSystem.prototype.stop = function () {
  20852. this._stopped = true;
  20853. };
  20854. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20855. var offset = index * 11;
  20856. this._vertices[offset] = particle.position.x;
  20857. this._vertices[offset + 1] = particle.position.y;
  20858. this._vertices[offset + 2] = particle.position.z;
  20859. this._vertices[offset + 3] = particle.color.r;
  20860. this._vertices[offset + 4] = particle.color.g;
  20861. this._vertices[offset + 5] = particle.color.b;
  20862. this._vertices[offset + 6] = particle.color.a;
  20863. this._vertices[offset + 7] = particle.angle;
  20864. this._vertices[offset + 8] = particle.size;
  20865. this._vertices[offset + 9] = offsetX;
  20866. this._vertices[offset + 10] = offsetY;
  20867. };
  20868. ParticleSystem.prototype._update = function (newParticles) {
  20869. // Update current
  20870. this._alive = this.particles.length > 0;
  20871. this.updateFunction(this.particles);
  20872. // Add new ones
  20873. var worldMatrix;
  20874. if (this.emitter.position) {
  20875. worldMatrix = this.emitter.getWorldMatrix();
  20876. }
  20877. else {
  20878. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20879. }
  20880. var particle;
  20881. for (var index = 0; index < newParticles; index++) {
  20882. if (this.particles.length === this._capacity) {
  20883. break;
  20884. }
  20885. if (this._stockParticles.length !== 0) {
  20886. particle = this._stockParticles.pop();
  20887. particle.age = 0;
  20888. }
  20889. else {
  20890. particle = new BABYLON.Particle();
  20891. }
  20892. this.particles.push(particle);
  20893. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20894. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  20895. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20896. particle.size = randomNumber(this.minSize, this.maxSize);
  20897. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20898. this.startPositionFunction(worldMatrix, particle.position, particle);
  20899. var step = randomNumber(0, 1.0);
  20900. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20901. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20902. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20903. }
  20904. };
  20905. ParticleSystem.prototype._getEffect = function () {
  20906. if (this._customEffect) {
  20907. return this._customEffect;
  20908. }
  20909. ;
  20910. var defines = [];
  20911. if (this._scene.clipPlane) {
  20912. defines.push("#define CLIPPLANE");
  20913. }
  20914. // Effect
  20915. var join = defines.join("\n");
  20916. if (this._cachedDefines !== join) {
  20917. this._cachedDefines = join;
  20918. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20919. }
  20920. return this._effect;
  20921. };
  20922. ParticleSystem.prototype.animate = function () {
  20923. if (!this._started)
  20924. return;
  20925. var effect = this._getEffect();
  20926. // Check
  20927. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20928. return;
  20929. if (this._currentRenderId === this._scene.getRenderId()) {
  20930. return;
  20931. }
  20932. this._currentRenderId = this._scene.getRenderId();
  20933. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20934. // determine the number of particles we need to create
  20935. var emitCout;
  20936. if (this.manualEmitCount > -1) {
  20937. emitCout = this.manualEmitCount;
  20938. this.manualEmitCount = 0;
  20939. }
  20940. else {
  20941. emitCout = this.emitRate;
  20942. }
  20943. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20944. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20945. if (this._newPartsExcess > 1.0) {
  20946. newParticles += this._newPartsExcess >> 0;
  20947. this._newPartsExcess -= this._newPartsExcess >> 0;
  20948. }
  20949. this._alive = false;
  20950. if (!this._stopped) {
  20951. this._actualFrame += this._scaledUpdateSpeed;
  20952. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20953. this.stop();
  20954. }
  20955. else {
  20956. newParticles = 0;
  20957. }
  20958. this._update(newParticles);
  20959. // Stopped?
  20960. if (this._stopped) {
  20961. if (!this._alive) {
  20962. this._started = false;
  20963. if (this.disposeOnStop) {
  20964. this._scene._toBeDisposed.push(this);
  20965. }
  20966. }
  20967. }
  20968. // Update VBO
  20969. var offset = 0;
  20970. for (var index = 0; index < this.particles.length; index++) {
  20971. var particle = this.particles[index];
  20972. this._appendParticleVertex(offset++, particle, 0, 0);
  20973. this._appendParticleVertex(offset++, particle, 1, 0);
  20974. this._appendParticleVertex(offset++, particle, 1, 1);
  20975. this._appendParticleVertex(offset++, particle, 0, 1);
  20976. }
  20977. var engine = this._scene.getEngine();
  20978. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20979. };
  20980. ParticleSystem.prototype.render = function () {
  20981. var effect = this._getEffect();
  20982. // Check
  20983. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20984. return 0;
  20985. var engine = this._scene.getEngine();
  20986. // Render
  20987. engine.enableEffect(effect);
  20988. engine.setState(false);
  20989. var viewMatrix = this._scene.getViewMatrix();
  20990. effect.setTexture("diffuseSampler", this.particleTexture);
  20991. effect.setMatrix("view", viewMatrix);
  20992. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20993. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20994. if (this._scene.clipPlane) {
  20995. var clipPlane = this._scene.clipPlane;
  20996. var invView = viewMatrix.clone();
  20997. invView.invert();
  20998. effect.setMatrix("invView", invView);
  20999. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21000. }
  21001. // VBOs
  21002. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21003. // Draw order
  21004. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21005. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21006. }
  21007. else {
  21008. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21009. }
  21010. if (this.forceDepthWrite) {
  21011. engine.setDepthWrite(true);
  21012. }
  21013. engine.draw(true, 0, this.particles.length * 6);
  21014. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21015. return this.particles.length;
  21016. };
  21017. ParticleSystem.prototype.dispose = function () {
  21018. if (this._vertexBuffer) {
  21019. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21020. this._vertexBuffer = null;
  21021. }
  21022. if (this._indexBuffer) {
  21023. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21024. this._indexBuffer = null;
  21025. }
  21026. if (this.particleTexture) {
  21027. this.particleTexture.dispose();
  21028. this.particleTexture = null;
  21029. }
  21030. // Remove from scene
  21031. var index = this._scene.particleSystems.indexOf(this);
  21032. this._scene.particleSystems.splice(index, 1);
  21033. // Callback
  21034. if (this.onDispose) {
  21035. this.onDispose();
  21036. }
  21037. };
  21038. // Clone
  21039. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21040. var result = new ParticleSystem(name, this._capacity, this._scene);
  21041. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21042. if (newEmitter === undefined) {
  21043. newEmitter = this.emitter;
  21044. }
  21045. result.emitter = newEmitter;
  21046. if (this.particleTexture) {
  21047. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21048. }
  21049. result.start();
  21050. return result;
  21051. };
  21052. ParticleSystem.prototype.serialize = function () {
  21053. var serializationObject = {};
  21054. serializationObject.name = this.name;
  21055. if (this.emitter.position) {
  21056. serializationObject.emitterId = this.emitter.id;
  21057. }
  21058. else {
  21059. serializationObject.emitter = this.emitter.asArray();
  21060. ;
  21061. }
  21062. serializationObject.capacity = this.getCapacity();
  21063. if (this.particleTexture) {
  21064. serializationObject.textureName = this.particleTexture.name;
  21065. }
  21066. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21067. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21068. serializationObject.minSize = this.minSize;
  21069. serializationObject.maxSize = this.maxSize;
  21070. serializationObject.minEmitPower = this.minEmitPower;
  21071. serializationObject.maxEmitPower = this.maxEmitPower;
  21072. serializationObject.minLifeTime = this.minLifeTime;
  21073. serializationObject.maxLifeTime = this.maxLifeTime;
  21074. serializationObject.emitRate = this.emitRate;
  21075. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21076. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21077. serializationObject.gravity = this.gravity.asArray();
  21078. serializationObject.direction1 = this.direction1.asArray();
  21079. serializationObject.direction2 = this.direction2.asArray();
  21080. serializationObject.color1 = this.color1.asArray();
  21081. serializationObject.color2 = this.color2.asArray();
  21082. serializationObject.colorDead = this.colorDead.asArray();
  21083. serializationObject.updateSpeed = this.updateSpeed;
  21084. serializationObject.targetStopDuration = this.targetStopDuration;
  21085. serializationObject.textureMask = this.textureMask.asArray();
  21086. serializationObject.blendMode = this.blendMode;
  21087. return serializationObject;
  21088. };
  21089. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21090. var name = parsedParticleSystem.name;
  21091. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21092. if (parsedParticleSystem.textureName) {
  21093. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21094. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21095. }
  21096. if (parsedParticleSystem.emitterId) {
  21097. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21098. }
  21099. else {
  21100. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21101. }
  21102. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21103. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21104. particleSystem.minSize = parsedParticleSystem.minSize;
  21105. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21106. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21107. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21108. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21109. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21110. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21111. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21112. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21113. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21114. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21115. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21116. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21117. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21118. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21119. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21120. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21121. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21122. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21123. particleSystem.start();
  21124. return particleSystem;
  21125. };
  21126. // Statics
  21127. ParticleSystem.BLENDMODE_ONEONE = 0;
  21128. ParticleSystem.BLENDMODE_STANDARD = 1;
  21129. return ParticleSystem;
  21130. })();
  21131. BABYLON.ParticleSystem = ParticleSystem;
  21132. })(BABYLON || (BABYLON = {}));
  21133. var BABYLON;
  21134. (function (BABYLON) {
  21135. var AnimationRange = (function () {
  21136. function AnimationRange(name, from, to) {
  21137. this.name = name;
  21138. this.from = from;
  21139. this.to = to;
  21140. }
  21141. return AnimationRange;
  21142. })();
  21143. BABYLON.AnimationRange = AnimationRange;
  21144. /**
  21145. * Composed of a frame, and an action function
  21146. */
  21147. var AnimationEvent = (function () {
  21148. function AnimationEvent(frame, action, onlyOnce) {
  21149. this.frame = frame;
  21150. this.action = action;
  21151. this.onlyOnce = onlyOnce;
  21152. this.isDone = false;
  21153. }
  21154. return AnimationEvent;
  21155. })();
  21156. BABYLON.AnimationEvent = AnimationEvent;
  21157. var Animation = (function () {
  21158. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21159. this.name = name;
  21160. this.targetProperty = targetProperty;
  21161. this.framePerSecond = framePerSecond;
  21162. this.dataType = dataType;
  21163. this.loopMode = loopMode;
  21164. this._offsetsCache = {};
  21165. this._highLimitsCache = {};
  21166. this._stopped = false;
  21167. // The set of event that will be linked to this animation
  21168. this._events = new Array();
  21169. this.allowMatricesInterpolation = false;
  21170. this._ranges = new Array();
  21171. this.targetPropertyPath = targetProperty.split(".");
  21172. this.dataType = dataType;
  21173. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21174. }
  21175. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21176. var dataType = undefined;
  21177. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21178. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21179. }
  21180. else if (from instanceof BABYLON.Quaternion) {
  21181. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21182. }
  21183. else if (from instanceof BABYLON.Vector3) {
  21184. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21185. }
  21186. else if (from instanceof BABYLON.Vector2) {
  21187. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21188. }
  21189. else if (from instanceof BABYLON.Color3) {
  21190. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21191. }
  21192. if (dataType == undefined) {
  21193. return null;
  21194. }
  21195. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21196. var keys = [];
  21197. keys.push({ frame: 0, value: from });
  21198. keys.push({ frame: totalFrame, value: to });
  21199. animation.setKeys(keys);
  21200. if (easingFunction !== undefined) {
  21201. animation.setEasingFunction(easingFunction);
  21202. }
  21203. return animation;
  21204. };
  21205. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21206. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21207. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21208. };
  21209. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21210. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21211. node.animations.push(animation);
  21212. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21213. };
  21214. // Methods
  21215. /**
  21216. * Add an event to this animation.
  21217. */
  21218. Animation.prototype.addEvent = function (event) {
  21219. this._events.push(event);
  21220. };
  21221. /**
  21222. * Remove all events found at the given frame
  21223. * @param frame
  21224. */
  21225. Animation.prototype.removeEvents = function (frame) {
  21226. for (var index = 0; index < this._events.length; index++) {
  21227. if (this._events[index].frame === frame) {
  21228. this._events.splice(index, 1);
  21229. index--;
  21230. }
  21231. }
  21232. };
  21233. Animation.prototype.createRange = function (name, from, to) {
  21234. this._ranges.push(new AnimationRange(name, from, to));
  21235. };
  21236. Animation.prototype.deleteRange = function (name) {
  21237. for (var index = 0; index < this._ranges.length; index++) {
  21238. if (this._ranges[index].name === name) {
  21239. this._ranges.splice(index, 1);
  21240. return;
  21241. }
  21242. }
  21243. };
  21244. Animation.prototype.getRange = function (name) {
  21245. for (var index = 0; index < this._ranges.length; index++) {
  21246. if (this._ranges[index].name === name) {
  21247. return this._ranges[index];
  21248. }
  21249. }
  21250. return null;
  21251. };
  21252. Animation.prototype.reset = function () {
  21253. this._offsetsCache = {};
  21254. this._highLimitsCache = {};
  21255. this.currentFrame = 0;
  21256. };
  21257. Animation.prototype.isStopped = function () {
  21258. return this._stopped;
  21259. };
  21260. Animation.prototype.getKeys = function () {
  21261. return this._keys;
  21262. };
  21263. Animation.prototype.getEasingFunction = function () {
  21264. return this._easingFunction;
  21265. };
  21266. Animation.prototype.setEasingFunction = function (easingFunction) {
  21267. this._easingFunction = easingFunction;
  21268. };
  21269. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21270. return startValue + (endValue - startValue) * gradient;
  21271. };
  21272. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21273. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21274. };
  21275. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21276. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21277. };
  21278. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21279. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21280. };
  21281. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21282. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21283. };
  21284. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21285. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21286. };
  21287. Animation.prototype.clone = function () {
  21288. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21289. if (this._keys) {
  21290. clone.setKeys(this._keys);
  21291. }
  21292. return clone;
  21293. };
  21294. Animation.prototype.setKeys = function (values) {
  21295. this._keys = values.slice(0);
  21296. this._offsetsCache = {};
  21297. this._highLimitsCache = {};
  21298. };
  21299. Animation.prototype._getKeyValue = function (value) {
  21300. if (typeof value === "function") {
  21301. return value();
  21302. }
  21303. return value;
  21304. };
  21305. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21306. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21307. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21308. }
  21309. this.currentFrame = currentFrame;
  21310. // Try to get a hash to find the right key
  21311. 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));
  21312. if (this._keys[startKey].frame >= currentFrame) {
  21313. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21314. startKey--;
  21315. }
  21316. }
  21317. for (var key = startKey; key < this._keys.length; key++) {
  21318. if (this._keys[key + 1].frame >= currentFrame) {
  21319. var startValue = this._getKeyValue(this._keys[key].value);
  21320. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21321. // gradient : percent of currentFrame between the frame inf and the frame sup
  21322. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21323. // check for easingFunction and correction of gradient
  21324. if (this._easingFunction != null) {
  21325. gradient = this._easingFunction.ease(gradient);
  21326. }
  21327. switch (this.dataType) {
  21328. // Float
  21329. case Animation.ANIMATIONTYPE_FLOAT:
  21330. switch (loopMode) {
  21331. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21332. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21333. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21334. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21335. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21336. }
  21337. break;
  21338. // Quaternion
  21339. case Animation.ANIMATIONTYPE_QUATERNION:
  21340. var quaternion = null;
  21341. switch (loopMode) {
  21342. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21343. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21344. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21345. break;
  21346. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21347. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21348. break;
  21349. }
  21350. return quaternion;
  21351. // Vector3
  21352. case Animation.ANIMATIONTYPE_VECTOR3:
  21353. switch (loopMode) {
  21354. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21355. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21356. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21357. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21358. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21359. }
  21360. // Vector2
  21361. case Animation.ANIMATIONTYPE_VECTOR2:
  21362. switch (loopMode) {
  21363. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21364. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21365. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21366. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21367. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21368. }
  21369. // Color3
  21370. case Animation.ANIMATIONTYPE_COLOR3:
  21371. switch (loopMode) {
  21372. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21373. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21374. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21375. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21376. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21377. }
  21378. // Matrix
  21379. case Animation.ANIMATIONTYPE_MATRIX:
  21380. switch (loopMode) {
  21381. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21382. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21383. if (this.allowMatricesInterpolation) {
  21384. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21385. }
  21386. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21387. return startValue;
  21388. }
  21389. default:
  21390. break;
  21391. }
  21392. break;
  21393. }
  21394. }
  21395. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21396. };
  21397. Animation.prototype.setValue = function (currentValue) {
  21398. // Set value
  21399. if (this.targetPropertyPath.length > 1) {
  21400. var property = this._target[this.targetPropertyPath[0]];
  21401. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21402. property = property[this.targetPropertyPath[index]];
  21403. }
  21404. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21405. }
  21406. else {
  21407. this._target[this.targetPropertyPath[0]] = currentValue;
  21408. }
  21409. if (this._target.markAsDirty) {
  21410. this._target.markAsDirty(this.targetProperty);
  21411. }
  21412. };
  21413. Animation.prototype.goToFrame = function (frame) {
  21414. if (frame < this._keys[0].frame) {
  21415. frame = this._keys[0].frame;
  21416. }
  21417. else if (frame > this._keys[this._keys.length - 1].frame) {
  21418. frame = this._keys[this._keys.length - 1].frame;
  21419. }
  21420. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21421. this.setValue(currentValue);
  21422. };
  21423. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21424. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21425. this._stopped = true;
  21426. return false;
  21427. }
  21428. var returnValue = true;
  21429. // Adding a start key at frame 0 if missing
  21430. if (this._keys[0].frame !== 0) {
  21431. var newKey = { frame: 0, value: this._keys[0].value };
  21432. this._keys.splice(0, 0, newKey);
  21433. }
  21434. // Check limits
  21435. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21436. from = this._keys[0].frame;
  21437. }
  21438. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21439. to = this._keys[this._keys.length - 1].frame;
  21440. }
  21441. // Compute ratio
  21442. var range = to - from;
  21443. var offsetValue;
  21444. // ratio represents the frame delta between from and to
  21445. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21446. var highLimitValue = 0;
  21447. if (ratio > range && !loop) {
  21448. returnValue = false;
  21449. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21450. }
  21451. else {
  21452. // Get max value if required
  21453. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21454. var keyOffset = to.toString() + from.toString();
  21455. if (!this._offsetsCache[keyOffset]) {
  21456. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21457. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21458. switch (this.dataType) {
  21459. // Float
  21460. case Animation.ANIMATIONTYPE_FLOAT:
  21461. this._offsetsCache[keyOffset] = toValue - fromValue;
  21462. break;
  21463. // Quaternion
  21464. case Animation.ANIMATIONTYPE_QUATERNION:
  21465. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21466. break;
  21467. // Vector3
  21468. case Animation.ANIMATIONTYPE_VECTOR3:
  21469. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21470. // Vector2
  21471. case Animation.ANIMATIONTYPE_VECTOR2:
  21472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21473. // Color3
  21474. case Animation.ANIMATIONTYPE_COLOR3:
  21475. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21476. default:
  21477. break;
  21478. }
  21479. this._highLimitsCache[keyOffset] = toValue;
  21480. }
  21481. highLimitValue = this._highLimitsCache[keyOffset];
  21482. offsetValue = this._offsetsCache[keyOffset];
  21483. }
  21484. }
  21485. if (offsetValue === undefined) {
  21486. switch (this.dataType) {
  21487. // Float
  21488. case Animation.ANIMATIONTYPE_FLOAT:
  21489. offsetValue = 0;
  21490. break;
  21491. // Quaternion
  21492. case Animation.ANIMATIONTYPE_QUATERNION:
  21493. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21494. break;
  21495. // Vector3
  21496. case Animation.ANIMATIONTYPE_VECTOR3:
  21497. offsetValue = BABYLON.Vector3.Zero();
  21498. break;
  21499. // Vector2
  21500. case Animation.ANIMATIONTYPE_VECTOR2:
  21501. offsetValue = BABYLON.Vector2.Zero();
  21502. break;
  21503. // Color3
  21504. case Animation.ANIMATIONTYPE_COLOR3:
  21505. offsetValue = BABYLON.Color3.Black();
  21506. }
  21507. }
  21508. // Compute value
  21509. var repeatCount = (ratio / range) >> 0;
  21510. var currentFrame = returnValue ? from + ratio % range : to;
  21511. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21512. // Check events
  21513. for (var index = 0; index < this._events.length; index++) {
  21514. if (currentFrame >= this._events[index].frame) {
  21515. var event = this._events[index];
  21516. if (!event.isDone) {
  21517. // If event should be done only once, remove it.
  21518. if (event.onlyOnce) {
  21519. this._events.splice(index, 1);
  21520. index--;
  21521. }
  21522. event.isDone = true;
  21523. event.action();
  21524. } // Don't do anything if the event has already be done.
  21525. }
  21526. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21527. // reset event, the animation is looping
  21528. this._events[index].isDone = false;
  21529. }
  21530. }
  21531. // Set value
  21532. this.setValue(currentValue);
  21533. if (!returnValue) {
  21534. this._stopped = true;
  21535. }
  21536. return returnValue;
  21537. };
  21538. Animation.prototype.serialize = function () {
  21539. var serializationObject = {};
  21540. serializationObject.name = this.name;
  21541. serializationObject.property = this.targetProperty;
  21542. serializationObject.framePerSecond = this.framePerSecond;
  21543. serializationObject.dataType = this.dataType;
  21544. serializationObject.loopBehavior = this.loopMode;
  21545. var dataType = this.dataType;
  21546. serializationObject.keys = [];
  21547. var keys = this.getKeys();
  21548. for (var index = 0; index < keys.length; index++) {
  21549. var animationKey = keys[index];
  21550. var key = {};
  21551. key.frame = animationKey.frame;
  21552. switch (dataType) {
  21553. case Animation.ANIMATIONTYPE_FLOAT:
  21554. key.values = [animationKey.value];
  21555. break;
  21556. case Animation.ANIMATIONTYPE_QUATERNION:
  21557. case Animation.ANIMATIONTYPE_MATRIX:
  21558. case Animation.ANIMATIONTYPE_VECTOR3:
  21559. key.values = animationKey.value.asArray();
  21560. break;
  21561. }
  21562. serializationObject.keys.push(key);
  21563. }
  21564. return serializationObject;
  21565. };
  21566. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21567. get: function () {
  21568. return Animation._ANIMATIONTYPE_FLOAT;
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21574. get: function () {
  21575. return Animation._ANIMATIONTYPE_VECTOR3;
  21576. },
  21577. enumerable: true,
  21578. configurable: true
  21579. });
  21580. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21581. get: function () {
  21582. return Animation._ANIMATIONTYPE_VECTOR2;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21588. get: function () {
  21589. return Animation._ANIMATIONTYPE_QUATERNION;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21595. get: function () {
  21596. return Animation._ANIMATIONTYPE_MATRIX;
  21597. },
  21598. enumerable: true,
  21599. configurable: true
  21600. });
  21601. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21602. get: function () {
  21603. return Animation._ANIMATIONTYPE_COLOR3;
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21609. get: function () {
  21610. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21616. get: function () {
  21617. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21623. get: function () {
  21624. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Animation.Parse = function (parsedAnimation) {
  21630. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21631. var dataType = parsedAnimation.dataType;
  21632. var keys = [];
  21633. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21634. var key = parsedAnimation.keys[index];
  21635. var data;
  21636. switch (dataType) {
  21637. case Animation.ANIMATIONTYPE_FLOAT:
  21638. data = key.values[0];
  21639. break;
  21640. case Animation.ANIMATIONTYPE_QUATERNION:
  21641. data = BABYLON.Quaternion.FromArray(key.values);
  21642. break;
  21643. case Animation.ANIMATIONTYPE_MATRIX:
  21644. data = BABYLON.Matrix.FromArray(key.values);
  21645. break;
  21646. case Animation.ANIMATIONTYPE_VECTOR3:
  21647. default:
  21648. data = BABYLON.Vector3.FromArray(key.values);
  21649. break;
  21650. }
  21651. keys.push({
  21652. frame: key.frame,
  21653. value: data
  21654. });
  21655. }
  21656. animation.setKeys(keys);
  21657. return animation;
  21658. };
  21659. Animation.AppendSerializedAnimations = function (source, destination) {
  21660. if (source.animations) {
  21661. destination.animations = [];
  21662. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21663. var animation = source.animations[animationIndex];
  21664. destination.animations.push(animation.serialize());
  21665. }
  21666. }
  21667. };
  21668. // Statics
  21669. Animation._ANIMATIONTYPE_FLOAT = 0;
  21670. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21671. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21672. Animation._ANIMATIONTYPE_MATRIX = 3;
  21673. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21674. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21675. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21676. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21677. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21678. return Animation;
  21679. })();
  21680. BABYLON.Animation = Animation;
  21681. })(BABYLON || (BABYLON = {}));
  21682. var BABYLON;
  21683. (function (BABYLON) {
  21684. var Animatable = (function () {
  21685. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21686. if (fromFrame === void 0) { fromFrame = 0; }
  21687. if (toFrame === void 0) { toFrame = 100; }
  21688. if (loopAnimation === void 0) { loopAnimation = false; }
  21689. if (speedRatio === void 0) { speedRatio = 1.0; }
  21690. this.target = target;
  21691. this.fromFrame = fromFrame;
  21692. this.toFrame = toFrame;
  21693. this.loopAnimation = loopAnimation;
  21694. this.speedRatio = speedRatio;
  21695. this.onAnimationEnd = onAnimationEnd;
  21696. this._animations = new Array();
  21697. this._paused = false;
  21698. this.animationStarted = false;
  21699. if (animations) {
  21700. this.appendAnimations(target, animations);
  21701. }
  21702. this._scene = scene;
  21703. scene._activeAnimatables.push(this);
  21704. }
  21705. // Methods
  21706. Animatable.prototype.getAnimations = function () {
  21707. return this._animations;
  21708. };
  21709. Animatable.prototype.appendAnimations = function (target, animations) {
  21710. for (var index = 0; index < animations.length; index++) {
  21711. var animation = animations[index];
  21712. animation._target = target;
  21713. this._animations.push(animation);
  21714. }
  21715. };
  21716. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21717. var animations = this._animations;
  21718. for (var index = 0; index < animations.length; index++) {
  21719. if (animations[index].targetProperty === property) {
  21720. return animations[index];
  21721. }
  21722. }
  21723. return null;
  21724. };
  21725. Animatable.prototype.reset = function () {
  21726. var animations = this._animations;
  21727. for (var index = 0; index < animations.length; index++) {
  21728. animations[index].reset();
  21729. }
  21730. this._localDelayOffset = null;
  21731. this._pausedDelay = null;
  21732. };
  21733. Animatable.prototype.goToFrame = function (frame) {
  21734. var animations = this._animations;
  21735. for (var index = 0; index < animations.length; index++) {
  21736. animations[index].goToFrame(frame);
  21737. }
  21738. };
  21739. Animatable.prototype.pause = function () {
  21740. if (this._paused) {
  21741. return;
  21742. }
  21743. this._paused = true;
  21744. };
  21745. Animatable.prototype.restart = function () {
  21746. this._paused = false;
  21747. };
  21748. Animatable.prototype.stop = function () {
  21749. var index = this._scene._activeAnimatables.indexOf(this);
  21750. if (index > -1) {
  21751. this._scene._activeAnimatables.splice(index, 1);
  21752. }
  21753. if (this.onAnimationEnd) {
  21754. this.onAnimationEnd();
  21755. }
  21756. };
  21757. Animatable.prototype._animate = function (delay) {
  21758. if (this._paused) {
  21759. this.animationStarted = false;
  21760. if (!this._pausedDelay) {
  21761. this._pausedDelay = delay;
  21762. }
  21763. return true;
  21764. }
  21765. if (!this._localDelayOffset) {
  21766. this._localDelayOffset = delay;
  21767. }
  21768. else if (this._pausedDelay) {
  21769. this._localDelayOffset += delay - this._pausedDelay;
  21770. this._pausedDelay = null;
  21771. }
  21772. // Animating
  21773. var running = false;
  21774. var animations = this._animations;
  21775. var index;
  21776. for (index = 0; index < animations.length; index++) {
  21777. var animation = animations[index];
  21778. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21779. running = running || isRunning;
  21780. }
  21781. this.animationStarted = running;
  21782. if (!running) {
  21783. // Remove from active animatables
  21784. index = this._scene._activeAnimatables.indexOf(this);
  21785. this._scene._activeAnimatables.splice(index, 1);
  21786. }
  21787. if (!running && this.onAnimationEnd) {
  21788. this.onAnimationEnd();
  21789. }
  21790. return running;
  21791. };
  21792. return Animatable;
  21793. })();
  21794. BABYLON.Animatable = Animatable;
  21795. })(BABYLON || (BABYLON = {}));
  21796. var BABYLON;
  21797. (function (BABYLON) {
  21798. var EasingFunction = (function () {
  21799. function EasingFunction() {
  21800. // Properties
  21801. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21802. }
  21803. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21804. get: function () {
  21805. return EasingFunction._EASINGMODE_EASEIN;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21811. get: function () {
  21812. return EasingFunction._EASINGMODE_EASEOUT;
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21818. get: function () {
  21819. return EasingFunction._EASINGMODE_EASEINOUT;
  21820. },
  21821. enumerable: true,
  21822. configurable: true
  21823. });
  21824. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21825. var n = Math.min(Math.max(easingMode, 0), 2);
  21826. this._easingMode = n;
  21827. };
  21828. EasingFunction.prototype.getEasingMode = function () {
  21829. return this._easingMode;
  21830. };
  21831. EasingFunction.prototype.easeInCore = function (gradient) {
  21832. throw new Error('You must implement this method');
  21833. };
  21834. EasingFunction.prototype.ease = function (gradient) {
  21835. switch (this._easingMode) {
  21836. case EasingFunction.EASINGMODE_EASEIN:
  21837. return this.easeInCore(gradient);
  21838. case EasingFunction.EASINGMODE_EASEOUT:
  21839. return (1 - this.easeInCore(1 - gradient));
  21840. }
  21841. if (gradient >= 0.5) {
  21842. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21843. }
  21844. return (this.easeInCore(gradient * 2) * 0.5);
  21845. };
  21846. //Statics
  21847. EasingFunction._EASINGMODE_EASEIN = 0;
  21848. EasingFunction._EASINGMODE_EASEOUT = 1;
  21849. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21850. return EasingFunction;
  21851. })();
  21852. BABYLON.EasingFunction = EasingFunction;
  21853. var CircleEase = (function (_super) {
  21854. __extends(CircleEase, _super);
  21855. function CircleEase() {
  21856. _super.apply(this, arguments);
  21857. }
  21858. CircleEase.prototype.easeInCore = function (gradient) {
  21859. gradient = Math.max(0, Math.min(1, gradient));
  21860. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21861. };
  21862. return CircleEase;
  21863. })(EasingFunction);
  21864. BABYLON.CircleEase = CircleEase;
  21865. var BackEase = (function (_super) {
  21866. __extends(BackEase, _super);
  21867. function BackEase(amplitude) {
  21868. if (amplitude === void 0) { amplitude = 1; }
  21869. _super.call(this);
  21870. this.amplitude = amplitude;
  21871. }
  21872. BackEase.prototype.easeInCore = function (gradient) {
  21873. var num = Math.max(0, this.amplitude);
  21874. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21875. };
  21876. return BackEase;
  21877. })(EasingFunction);
  21878. BABYLON.BackEase = BackEase;
  21879. var BounceEase = (function (_super) {
  21880. __extends(BounceEase, _super);
  21881. function BounceEase(bounces, bounciness) {
  21882. if (bounces === void 0) { bounces = 3; }
  21883. if (bounciness === void 0) { bounciness = 2; }
  21884. _super.call(this);
  21885. this.bounces = bounces;
  21886. this.bounciness = bounciness;
  21887. }
  21888. BounceEase.prototype.easeInCore = function (gradient) {
  21889. var y = Math.max(0.0, this.bounces);
  21890. var bounciness = this.bounciness;
  21891. if (bounciness <= 1.0) {
  21892. bounciness = 1.001;
  21893. }
  21894. var num9 = Math.pow(bounciness, y);
  21895. var num5 = 1.0 - bounciness;
  21896. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21897. var num15 = gradient * num4;
  21898. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21899. var num3 = Math.floor(num65);
  21900. var num13 = num3 + 1.0;
  21901. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21902. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21903. var num7 = (num8 + num12) * 0.5;
  21904. var num6 = gradient - num7;
  21905. var num2 = num7 - num8;
  21906. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21907. };
  21908. return BounceEase;
  21909. })(EasingFunction);
  21910. BABYLON.BounceEase = BounceEase;
  21911. var CubicEase = (function (_super) {
  21912. __extends(CubicEase, _super);
  21913. function CubicEase() {
  21914. _super.apply(this, arguments);
  21915. }
  21916. CubicEase.prototype.easeInCore = function (gradient) {
  21917. return (gradient * gradient * gradient);
  21918. };
  21919. return CubicEase;
  21920. })(EasingFunction);
  21921. BABYLON.CubicEase = CubicEase;
  21922. var ElasticEase = (function (_super) {
  21923. __extends(ElasticEase, _super);
  21924. function ElasticEase(oscillations, springiness) {
  21925. if (oscillations === void 0) { oscillations = 3; }
  21926. if (springiness === void 0) { springiness = 3; }
  21927. _super.call(this);
  21928. this.oscillations = oscillations;
  21929. this.springiness = springiness;
  21930. }
  21931. ElasticEase.prototype.easeInCore = function (gradient) {
  21932. var num2;
  21933. var num3 = Math.max(0.0, this.oscillations);
  21934. var num = Math.max(0.0, this.springiness);
  21935. if (num == 0) {
  21936. num2 = gradient;
  21937. }
  21938. else {
  21939. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21940. }
  21941. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21942. };
  21943. return ElasticEase;
  21944. })(EasingFunction);
  21945. BABYLON.ElasticEase = ElasticEase;
  21946. var ExponentialEase = (function (_super) {
  21947. __extends(ExponentialEase, _super);
  21948. function ExponentialEase(exponent) {
  21949. if (exponent === void 0) { exponent = 2; }
  21950. _super.call(this);
  21951. this.exponent = exponent;
  21952. }
  21953. ExponentialEase.prototype.easeInCore = function (gradient) {
  21954. if (this.exponent <= 0) {
  21955. return gradient;
  21956. }
  21957. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21958. };
  21959. return ExponentialEase;
  21960. })(EasingFunction);
  21961. BABYLON.ExponentialEase = ExponentialEase;
  21962. var PowerEase = (function (_super) {
  21963. __extends(PowerEase, _super);
  21964. function PowerEase(power) {
  21965. if (power === void 0) { power = 2; }
  21966. _super.call(this);
  21967. this.power = power;
  21968. }
  21969. PowerEase.prototype.easeInCore = function (gradient) {
  21970. var y = Math.max(0.0, this.power);
  21971. return Math.pow(gradient, y);
  21972. };
  21973. return PowerEase;
  21974. })(EasingFunction);
  21975. BABYLON.PowerEase = PowerEase;
  21976. var QuadraticEase = (function (_super) {
  21977. __extends(QuadraticEase, _super);
  21978. function QuadraticEase() {
  21979. _super.apply(this, arguments);
  21980. }
  21981. QuadraticEase.prototype.easeInCore = function (gradient) {
  21982. return (gradient * gradient);
  21983. };
  21984. return QuadraticEase;
  21985. })(EasingFunction);
  21986. BABYLON.QuadraticEase = QuadraticEase;
  21987. var QuarticEase = (function (_super) {
  21988. __extends(QuarticEase, _super);
  21989. function QuarticEase() {
  21990. _super.apply(this, arguments);
  21991. }
  21992. QuarticEase.prototype.easeInCore = function (gradient) {
  21993. return (gradient * gradient * gradient * gradient);
  21994. };
  21995. return QuarticEase;
  21996. })(EasingFunction);
  21997. BABYLON.QuarticEase = QuarticEase;
  21998. var QuinticEase = (function (_super) {
  21999. __extends(QuinticEase, _super);
  22000. function QuinticEase() {
  22001. _super.apply(this, arguments);
  22002. }
  22003. QuinticEase.prototype.easeInCore = function (gradient) {
  22004. return (gradient * gradient * gradient * gradient * gradient);
  22005. };
  22006. return QuinticEase;
  22007. })(EasingFunction);
  22008. BABYLON.QuinticEase = QuinticEase;
  22009. var SineEase = (function (_super) {
  22010. __extends(SineEase, _super);
  22011. function SineEase() {
  22012. _super.apply(this, arguments);
  22013. }
  22014. SineEase.prototype.easeInCore = function (gradient) {
  22015. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22016. };
  22017. return SineEase;
  22018. })(EasingFunction);
  22019. BABYLON.SineEase = SineEase;
  22020. var BezierCurveEase = (function (_super) {
  22021. __extends(BezierCurveEase, _super);
  22022. function BezierCurveEase(x1, y1, x2, y2) {
  22023. if (x1 === void 0) { x1 = 0; }
  22024. if (y1 === void 0) { y1 = 0; }
  22025. if (x2 === void 0) { x2 = 1; }
  22026. if (y2 === void 0) { y2 = 1; }
  22027. _super.call(this);
  22028. this.x1 = x1;
  22029. this.y1 = y1;
  22030. this.x2 = x2;
  22031. this.y2 = y2;
  22032. }
  22033. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22034. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22035. };
  22036. return BezierCurveEase;
  22037. })(EasingFunction);
  22038. BABYLON.BezierCurveEase = BezierCurveEase;
  22039. })(BABYLON || (BABYLON = {}));
  22040. var BABYLON;
  22041. (function (BABYLON) {
  22042. var Bone = (function (_super) {
  22043. __extends(Bone, _super);
  22044. function Bone(name, skeleton, parentBone, matrix) {
  22045. _super.call(this, name, skeleton.getScene());
  22046. this.name = name;
  22047. this.children = new Array();
  22048. this.animations = new Array();
  22049. this._worldTransform = new BABYLON.Matrix();
  22050. this._absoluteTransform = new BABYLON.Matrix();
  22051. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22052. this._skeleton = skeleton;
  22053. this._matrix = matrix;
  22054. this._baseMatrix = matrix;
  22055. skeleton.bones.push(this);
  22056. if (parentBone) {
  22057. this._parent = parentBone;
  22058. parentBone.children.push(this);
  22059. }
  22060. else {
  22061. this._parent = null;
  22062. }
  22063. this._updateDifferenceMatrix();
  22064. }
  22065. // Members
  22066. Bone.prototype.getParent = function () {
  22067. return this._parent;
  22068. };
  22069. Bone.prototype.getLocalMatrix = function () {
  22070. return this._matrix;
  22071. };
  22072. Bone.prototype.getBaseMatrix = function () {
  22073. return this._baseMatrix;
  22074. };
  22075. Bone.prototype.getWorldMatrix = function () {
  22076. return this._worldTransform;
  22077. };
  22078. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22079. return this._invertedAbsoluteTransform;
  22080. };
  22081. Bone.prototype.getAbsoluteMatrix = function () {
  22082. var matrix = this._matrix.clone();
  22083. var parent = this._parent;
  22084. while (parent) {
  22085. matrix = matrix.multiply(parent.getLocalMatrix());
  22086. parent = parent.getParent();
  22087. }
  22088. return matrix;
  22089. };
  22090. // Methods
  22091. Bone.prototype.updateMatrix = function (matrix) {
  22092. this._matrix = matrix;
  22093. this._skeleton._markAsDirty();
  22094. this._updateDifferenceMatrix();
  22095. };
  22096. Bone.prototype._updateDifferenceMatrix = function () {
  22097. if (this._parent) {
  22098. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22099. }
  22100. else {
  22101. this._absoluteTransform.copyFrom(this._matrix);
  22102. }
  22103. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22104. for (var index = 0; index < this.children.length; index++) {
  22105. this.children[index]._updateDifferenceMatrix();
  22106. }
  22107. };
  22108. Bone.prototype.markAsDirty = function () {
  22109. this._currentRenderId++;
  22110. this._skeleton._markAsDirty();
  22111. };
  22112. return Bone;
  22113. })(BABYLON.Node);
  22114. BABYLON.Bone = Bone;
  22115. })(BABYLON || (BABYLON = {}));
  22116. var BABYLON;
  22117. (function (BABYLON) {
  22118. var Skeleton = (function () {
  22119. function Skeleton(name, id, scene) {
  22120. this.name = name;
  22121. this.id = id;
  22122. this.bones = new Array();
  22123. this._isDirty = true;
  22124. this._identity = BABYLON.Matrix.Identity();
  22125. this._ranges = new Array();
  22126. this.bones = [];
  22127. this._scene = scene;
  22128. scene.skeletons.push(this);
  22129. this.prepare();
  22130. //make sure it will recalculate the matrix next time prepare is called.
  22131. this._isDirty = true;
  22132. }
  22133. // Members
  22134. Skeleton.prototype.getTransformMatrices = function () {
  22135. return this._transformMatrices;
  22136. };
  22137. Skeleton.prototype.getScene = function () {
  22138. return this._scene;
  22139. };
  22140. // Methods
  22141. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22142. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22143. };
  22144. Skeleton.prototype.deleteAnimationRange = function (name) {
  22145. for (var index = 0; index < this._ranges.length; index++) {
  22146. if (this._ranges[index].name === name) {
  22147. this._ranges.splice(index, 1);
  22148. return;
  22149. }
  22150. }
  22151. };
  22152. Skeleton.prototype.getAnimationRange = function (name) {
  22153. for (var index = 0; index < this._ranges.length; index++) {
  22154. if (this._ranges[index].name === name) {
  22155. return this._ranges[index];
  22156. }
  22157. }
  22158. return null;
  22159. };
  22160. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22161. var range = this.getAnimationRange(name);
  22162. if (!range) {
  22163. return null;
  22164. }
  22165. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22166. };
  22167. Skeleton.prototype._markAsDirty = function () {
  22168. this._isDirty = true;
  22169. };
  22170. Skeleton.prototype.prepare = function () {
  22171. if (!this._isDirty) {
  22172. return;
  22173. }
  22174. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22175. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22176. }
  22177. for (var index = 0; index < this.bones.length; index++) {
  22178. var bone = this.bones[index];
  22179. var parentBone = bone.getParent();
  22180. if (parentBone) {
  22181. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22182. }
  22183. else {
  22184. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22185. }
  22186. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22187. }
  22188. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22189. this._isDirty = false;
  22190. this._scene._activeBones += this.bones.length;
  22191. };
  22192. Skeleton.prototype.getAnimatables = function () {
  22193. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22194. this._animatables = [];
  22195. for (var index = 0; index < this.bones.length; index++) {
  22196. this._animatables.push(this.bones[index]);
  22197. }
  22198. }
  22199. return this._animatables;
  22200. };
  22201. Skeleton.prototype.clone = function (name, id) {
  22202. var result = new Skeleton(name, id || name, this._scene);
  22203. for (var index = 0; index < this.bones.length; index++) {
  22204. var source = this.bones[index];
  22205. var parentBone = null;
  22206. if (source.getParent()) {
  22207. var parentIndex = this.bones.indexOf(source.getParent());
  22208. parentBone = result.bones[parentIndex];
  22209. }
  22210. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22211. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22212. }
  22213. return result;
  22214. };
  22215. Skeleton.prototype.dispose = function () {
  22216. // Animations
  22217. this.getScene().stopAnimation(this);
  22218. // Remove from scene
  22219. this.getScene().removeSkeleton(this);
  22220. };
  22221. Skeleton.prototype.serialize = function () {
  22222. var serializationObject = {};
  22223. serializationObject.name = this.name;
  22224. serializationObject.id = this.id;
  22225. serializationObject.bones = [];
  22226. for (var index = 0; index < this.bones.length; index++) {
  22227. var bone = this.bones[index];
  22228. var serializedBone = {
  22229. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22230. name: bone.name,
  22231. matrix: bone.getLocalMatrix().toArray()
  22232. };
  22233. serializationObject.bones.push(serializedBone);
  22234. if (bone.animations && bone.animations.length > 0) {
  22235. serializedBone.animation = bone.animations[0].serialize();
  22236. }
  22237. }
  22238. return serializationObject;
  22239. };
  22240. Skeleton.Parse = function (parsedSkeleton, scene) {
  22241. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22242. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22243. var parsedBone = parsedSkeleton.bones[index];
  22244. var parentBone = null;
  22245. if (parsedBone.parentBoneIndex > -1) {
  22246. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22247. }
  22248. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22249. if (parsedBone.animation) {
  22250. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22251. }
  22252. }
  22253. return skeleton;
  22254. };
  22255. return Skeleton;
  22256. })();
  22257. BABYLON.Skeleton = Skeleton;
  22258. })(BABYLON || (BABYLON = {}));
  22259. var BABYLON;
  22260. (function (BABYLON) {
  22261. var PostProcess = (function () {
  22262. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22264. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22265. this.name = name;
  22266. this.width = -1;
  22267. this.height = -1;
  22268. this._reusable = false;
  22269. this._textures = new BABYLON.SmartArray(2);
  22270. this._currentRenderTextureInd = 0;
  22271. if (camera != null) {
  22272. this._camera = camera;
  22273. this._scene = camera.getScene();
  22274. camera.attachPostProcess(this);
  22275. this._engine = this._scene.getEngine();
  22276. }
  22277. else {
  22278. this._engine = engine;
  22279. }
  22280. this._renderRatio = ratio;
  22281. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22282. this._reusable = reusable || false;
  22283. this._textureType = textureType;
  22284. this._samplers = samplers || [];
  22285. this._samplers.push("textureSampler");
  22286. this._fragmentUrl = fragmentUrl;
  22287. this._parameters = parameters || [];
  22288. this.updateEffect(defines);
  22289. }
  22290. PostProcess.prototype.updateEffect = function (defines) {
  22291. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22292. };
  22293. PostProcess.prototype.isReusable = function () {
  22294. return this._reusable;
  22295. };
  22296. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22297. camera = camera || this._camera;
  22298. var scene = camera.getScene();
  22299. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22300. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22301. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22302. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22303. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22304. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22305. if (this._textures.length > 0) {
  22306. for (var i = 0; i < this._textures.length; i++) {
  22307. this._engine._releaseTexture(this._textures.data[i]);
  22308. }
  22309. this._textures.reset();
  22310. }
  22311. this.width = desiredWidth;
  22312. this.height = desiredHeight;
  22313. 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 }));
  22314. if (this._reusable) {
  22315. 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 }));
  22316. }
  22317. if (this.onSizeChanged) {
  22318. this.onSizeChanged();
  22319. }
  22320. }
  22321. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22322. if (this.onActivate) {
  22323. this.onActivate(camera);
  22324. }
  22325. // Clear
  22326. if (this.clearColor) {
  22327. this._engine.clear(this.clearColor, true, true);
  22328. }
  22329. else {
  22330. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22331. }
  22332. if (this._reusable) {
  22333. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22334. }
  22335. };
  22336. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22337. get: function () {
  22338. return this._effect.isSupported;
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. PostProcess.prototype.apply = function () {
  22344. // Check
  22345. if (!this._effect.isReady())
  22346. return null;
  22347. // States
  22348. this._engine.enableEffect(this._effect);
  22349. this._engine.setState(false);
  22350. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22351. this._engine.setDepthBuffer(false);
  22352. this._engine.setDepthWrite(false);
  22353. // Texture
  22354. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22355. // Parameters
  22356. if (this.onApply) {
  22357. this.onApply(this._effect);
  22358. }
  22359. return this._effect;
  22360. };
  22361. PostProcess.prototype.dispose = function (camera) {
  22362. camera = camera || this._camera;
  22363. if (this._textures.length > 0) {
  22364. for (var i = 0; i < this._textures.length; i++) {
  22365. this._engine._releaseTexture(this._textures.data[i]);
  22366. }
  22367. this._textures.reset();
  22368. }
  22369. if (!camera) {
  22370. return;
  22371. }
  22372. camera.detachPostProcess(this);
  22373. var index = camera._postProcesses.indexOf(this);
  22374. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22375. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22376. }
  22377. };
  22378. return PostProcess;
  22379. })();
  22380. BABYLON.PostProcess = PostProcess;
  22381. })(BABYLON || (BABYLON = {}));
  22382. var BABYLON;
  22383. (function (BABYLON) {
  22384. var PostProcessManager = (function () {
  22385. function PostProcessManager(scene) {
  22386. this._vertexDeclaration = [2];
  22387. this._vertexStrideSize = 2 * 4;
  22388. this._scene = scene;
  22389. }
  22390. PostProcessManager.prototype._prepareBuffers = function () {
  22391. if (this._vertexBuffer) {
  22392. return;
  22393. }
  22394. // VBO
  22395. var vertices = [];
  22396. vertices.push(1, 1);
  22397. vertices.push(-1, 1);
  22398. vertices.push(-1, -1);
  22399. vertices.push(1, -1);
  22400. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22401. // Indices
  22402. var indices = [];
  22403. indices.push(0);
  22404. indices.push(1);
  22405. indices.push(2);
  22406. indices.push(0);
  22407. indices.push(2);
  22408. indices.push(3);
  22409. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22410. };
  22411. // Methods
  22412. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22413. var postProcesses = this._scene.activeCamera._postProcesses;
  22414. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22415. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22416. return false;
  22417. }
  22418. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22419. return true;
  22420. };
  22421. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22422. var engine = this._scene.getEngine();
  22423. for (var index = 0; index < postProcesses.length; index++) {
  22424. if (index < postProcesses.length - 1) {
  22425. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22426. }
  22427. else {
  22428. if (targetTexture) {
  22429. engine.bindFramebuffer(targetTexture);
  22430. }
  22431. else {
  22432. engine.restoreDefaultFramebuffer();
  22433. }
  22434. }
  22435. var pp = postProcesses[index];
  22436. var effect = pp.apply();
  22437. if (effect) {
  22438. if (pp.onBeforeRender) {
  22439. pp.onBeforeRender(effect);
  22440. }
  22441. // VBOs
  22442. this._prepareBuffers();
  22443. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22444. // Draw order
  22445. engine.draw(true, 0, 6);
  22446. if (pp.onAfterRender) {
  22447. pp.onAfterRender(effect);
  22448. }
  22449. }
  22450. }
  22451. // Restore depth buffer
  22452. engine.setDepthBuffer(true);
  22453. engine.setDepthWrite(true);
  22454. };
  22455. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22456. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22457. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22458. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22459. return;
  22460. }
  22461. var engine = this._scene.getEngine();
  22462. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22463. if (index < postProcessesTakenIndices.length - 1) {
  22464. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22465. }
  22466. else {
  22467. if (targetTexture) {
  22468. engine.bindFramebuffer(targetTexture, faceIndex);
  22469. }
  22470. else {
  22471. engine.restoreDefaultFramebuffer();
  22472. }
  22473. }
  22474. if (doNotPresent) {
  22475. break;
  22476. }
  22477. var pp = postProcesses[postProcessesTakenIndices[index]];
  22478. var effect = pp.apply();
  22479. if (effect) {
  22480. if (pp.onBeforeRender) {
  22481. pp.onBeforeRender(effect);
  22482. }
  22483. // VBOs
  22484. this._prepareBuffers();
  22485. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22486. // Draw order
  22487. engine.draw(true, 0, 6);
  22488. if (pp.onAfterRender) {
  22489. pp.onAfterRender(effect);
  22490. }
  22491. }
  22492. }
  22493. // Restore depth buffer
  22494. engine.setDepthBuffer(true);
  22495. engine.setDepthWrite(true);
  22496. };
  22497. PostProcessManager.prototype.dispose = function () {
  22498. if (this._vertexBuffer) {
  22499. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22500. this._vertexBuffer = null;
  22501. }
  22502. if (this._indexBuffer) {
  22503. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22504. this._indexBuffer = null;
  22505. }
  22506. };
  22507. return PostProcessManager;
  22508. })();
  22509. BABYLON.PostProcessManager = PostProcessManager;
  22510. })(BABYLON || (BABYLON = {}));
  22511. var BABYLON;
  22512. (function (BABYLON) {
  22513. var PassPostProcess = (function (_super) {
  22514. __extends(PassPostProcess, _super);
  22515. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22516. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22517. }
  22518. return PassPostProcess;
  22519. })(BABYLON.PostProcess);
  22520. BABYLON.PassPostProcess = PassPostProcess;
  22521. })(BABYLON || (BABYLON = {}));
  22522. var BABYLON;
  22523. (function (BABYLON) {
  22524. var PhysicsEngine = (function () {
  22525. function PhysicsEngine(plugin) {
  22526. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22527. }
  22528. PhysicsEngine.prototype._initialize = function (gravity) {
  22529. this._currentPlugin.initialize();
  22530. this._setGravity(gravity);
  22531. };
  22532. PhysicsEngine.prototype._runOneStep = function (delta) {
  22533. if (delta > 0.1) {
  22534. delta = 0.1;
  22535. }
  22536. else if (delta <= 0) {
  22537. delta = 1.0 / 60.0;
  22538. }
  22539. this._currentPlugin.runOneStep(delta);
  22540. };
  22541. PhysicsEngine.prototype._setGravity = function (gravity) {
  22542. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22543. this._currentPlugin.setGravity(this.gravity);
  22544. };
  22545. PhysicsEngine.prototype._getGravity = function () {
  22546. return this._currentPlugin.getGravity();
  22547. };
  22548. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22549. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22550. };
  22551. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22552. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22553. };
  22554. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22555. this._currentPlugin.unregisterMesh(mesh);
  22556. };
  22557. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22558. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22559. };
  22560. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22561. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22562. };
  22563. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22564. this._currentPlugin.updateBodyPosition(mesh);
  22565. };
  22566. PhysicsEngine.prototype.dispose = function () {
  22567. this._currentPlugin.dispose();
  22568. };
  22569. PhysicsEngine.prototype.isSupported = function () {
  22570. return this._currentPlugin.isSupported();
  22571. };
  22572. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22573. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22574. };
  22575. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22576. return this._currentPlugin.name;
  22577. };
  22578. // Statics
  22579. PhysicsEngine.NoImpostor = 0;
  22580. PhysicsEngine.SphereImpostor = 1;
  22581. PhysicsEngine.BoxImpostor = 2;
  22582. PhysicsEngine.PlaneImpostor = 3;
  22583. PhysicsEngine.MeshImpostor = 4;
  22584. PhysicsEngine.CapsuleImpostor = 5;
  22585. PhysicsEngine.ConeImpostor = 6;
  22586. PhysicsEngine.CylinderImpostor = 7;
  22587. PhysicsEngine.ConvexHullImpostor = 8;
  22588. PhysicsEngine.HeightmapImpostor = 9;
  22589. PhysicsEngine.Epsilon = 0.001;
  22590. return PhysicsEngine;
  22591. })();
  22592. BABYLON.PhysicsEngine = PhysicsEngine;
  22593. })(BABYLON || (BABYLON = {}));
  22594. var BABYLON;
  22595. (function (BABYLON) {
  22596. var VertexData = (function () {
  22597. function VertexData() {
  22598. }
  22599. VertexData.prototype.set = function (data, kind) {
  22600. switch (kind) {
  22601. case BABYLON.VertexBuffer.PositionKind:
  22602. this.positions = data;
  22603. break;
  22604. case BABYLON.VertexBuffer.NormalKind:
  22605. this.normals = data;
  22606. break;
  22607. case BABYLON.VertexBuffer.UVKind:
  22608. this.uvs = data;
  22609. break;
  22610. case BABYLON.VertexBuffer.UV2Kind:
  22611. this.uvs2 = data;
  22612. break;
  22613. case BABYLON.VertexBuffer.UV3Kind:
  22614. this.uvs3 = data;
  22615. break;
  22616. case BABYLON.VertexBuffer.UV4Kind:
  22617. this.uvs4 = data;
  22618. break;
  22619. case BABYLON.VertexBuffer.UV5Kind:
  22620. this.uvs5 = data;
  22621. break;
  22622. case BABYLON.VertexBuffer.UV6Kind:
  22623. this.uvs6 = data;
  22624. break;
  22625. case BABYLON.VertexBuffer.ColorKind:
  22626. this.colors = data;
  22627. break;
  22628. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22629. this.matricesIndices = data;
  22630. break;
  22631. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22632. this.matricesWeights = data;
  22633. break;
  22634. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22635. this.matricesIndicesExtra = data;
  22636. break;
  22637. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22638. this.matricesWeightsExtra = data;
  22639. break;
  22640. }
  22641. };
  22642. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22643. this._applyTo(mesh, updatable);
  22644. };
  22645. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22646. this._applyTo(geometry, updatable);
  22647. };
  22648. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22649. this._update(mesh);
  22650. };
  22651. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22652. this._update(geometry);
  22653. };
  22654. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22655. if (this.positions) {
  22656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22657. }
  22658. if (this.normals) {
  22659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22660. }
  22661. if (this.uvs) {
  22662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22663. }
  22664. if (this.uvs2) {
  22665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22666. }
  22667. if (this.uvs3) {
  22668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22669. }
  22670. if (this.uvs4) {
  22671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22672. }
  22673. if (this.uvs5) {
  22674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22675. }
  22676. if (this.uvs6) {
  22677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22678. }
  22679. if (this.colors) {
  22680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22681. }
  22682. if (this.matricesIndices) {
  22683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22684. }
  22685. if (this.matricesWeights) {
  22686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22687. }
  22688. if (this.matricesIndicesExtra) {
  22689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22690. }
  22691. if (this.matricesWeightsExtra) {
  22692. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22693. }
  22694. if (this.indices) {
  22695. meshOrGeometry.setIndices(this.indices);
  22696. }
  22697. };
  22698. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22699. if (this.positions) {
  22700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22701. }
  22702. if (this.normals) {
  22703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22704. }
  22705. if (this.uvs) {
  22706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22707. }
  22708. if (this.uvs2) {
  22709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22710. }
  22711. if (this.uvs3) {
  22712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22713. }
  22714. if (this.uvs4) {
  22715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22716. }
  22717. if (this.uvs5) {
  22718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22719. }
  22720. if (this.uvs6) {
  22721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22722. }
  22723. if (this.colors) {
  22724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22725. }
  22726. if (this.matricesIndices) {
  22727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22728. }
  22729. if (this.matricesWeights) {
  22730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22731. }
  22732. if (this.matricesIndicesExtra) {
  22733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22734. }
  22735. if (this.matricesWeightsExtra) {
  22736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22737. }
  22738. if (this.indices) {
  22739. meshOrGeometry.setIndices(this.indices);
  22740. }
  22741. };
  22742. VertexData.prototype.transform = function (matrix) {
  22743. var transformed = BABYLON.Vector3.Zero();
  22744. var index;
  22745. if (this.positions) {
  22746. var position = BABYLON.Vector3.Zero();
  22747. for (index = 0; index < this.positions.length; index += 3) {
  22748. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22749. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22750. this.positions[index] = transformed.x;
  22751. this.positions[index + 1] = transformed.y;
  22752. this.positions[index + 2] = transformed.z;
  22753. }
  22754. }
  22755. if (this.normals) {
  22756. var normal = BABYLON.Vector3.Zero();
  22757. for (index = 0; index < this.normals.length; index += 3) {
  22758. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22759. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22760. this.normals[index] = transformed.x;
  22761. this.normals[index + 1] = transformed.y;
  22762. this.normals[index + 2] = transformed.z;
  22763. }
  22764. }
  22765. };
  22766. VertexData.prototype.merge = function (other) {
  22767. if (other.indices) {
  22768. if (!this.indices) {
  22769. this.indices = [];
  22770. }
  22771. var offset = this.positions ? this.positions.length / 3 : 0;
  22772. for (var index = 0; index < other.indices.length; index++) {
  22773. //TODO check type - if Int32Array!
  22774. this.indices.push(other.indices[index] + offset);
  22775. }
  22776. }
  22777. this.positions = this._mergeElement(this.positions, other.positions);
  22778. this.normals = this._mergeElement(this.normals, other.normals);
  22779. this.uvs = this._mergeElement(this.uvs, other.uvs);
  22780. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  22781. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  22782. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  22783. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  22784. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  22785. this.colors = this._mergeElement(this.colors, other.colors);
  22786. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  22787. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  22788. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  22789. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  22790. };
  22791. VertexData.prototype._mergeElement = function (source, other) {
  22792. if (!other)
  22793. return source;
  22794. if (!source)
  22795. return other;
  22796. var len = other.length + source.length;
  22797. var isSrcTypedArray = source instanceof Float32Array;
  22798. var isOthTypedArray = other instanceof Float32Array;
  22799. // use non-loop method when the source is Float32Array
  22800. if (isSrcTypedArray) {
  22801. var ret32 = new Float32Array(len);
  22802. ret32.set(source);
  22803. ret32.set(other, source.length);
  22804. return ret32;
  22805. }
  22806. else if (!isOthTypedArray) {
  22807. return source.concat(other);
  22808. }
  22809. else {
  22810. var ret = source.slice(0); // copy source to a separate array
  22811. for (var i = 0, len = other.length; i < len; i++) {
  22812. ret.push(other[i]);
  22813. }
  22814. return ret;
  22815. }
  22816. };
  22817. VertexData.prototype.serialize = function () {
  22818. var serializationObject = this.serialize();
  22819. if (this.positions) {
  22820. serializationObject.positions = this.positions;
  22821. }
  22822. if (this.normals) {
  22823. serializationObject.normals = this.normals;
  22824. }
  22825. if (this.uvs) {
  22826. serializationObject.uvs = this.uvs;
  22827. }
  22828. if (this.uvs2) {
  22829. serializationObject.uvs2 = this.uvs2;
  22830. }
  22831. if (this.uvs3) {
  22832. serializationObject.uvs3 = this.uvs3;
  22833. }
  22834. if (this.uvs4) {
  22835. serializationObject.uvs4 = this.uvs4;
  22836. }
  22837. if (this.uvs5) {
  22838. serializationObject.uvs5 = this.uvs5;
  22839. }
  22840. if (this.uvs6) {
  22841. serializationObject.uvs6 = this.uvs6;
  22842. }
  22843. if (this.colors) {
  22844. serializationObject.colors = this.colors;
  22845. }
  22846. if (this.matricesIndices) {
  22847. serializationObject.matricesIndices = this.matricesIndices;
  22848. serializationObject.matricesIndices._isExpanded = true;
  22849. }
  22850. if (this.matricesWeights) {
  22851. serializationObject.matricesWeights = this.matricesWeights;
  22852. }
  22853. if (this.matricesIndicesExtra) {
  22854. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  22855. serializationObject.matricesIndicesExtra._isExpanded = true;
  22856. }
  22857. if (this.matricesWeightsExtra) {
  22858. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  22859. }
  22860. serializationObject.indices = this.indices;
  22861. return serializationObject;
  22862. };
  22863. // Statics
  22864. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22865. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22866. };
  22867. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22868. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22869. };
  22870. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22871. var result = new VertexData();
  22872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22873. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22874. }
  22875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22876. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22877. }
  22878. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22879. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22880. }
  22881. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22882. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22883. }
  22884. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22885. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22886. }
  22887. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22888. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22889. }
  22890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22891. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22892. }
  22893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22894. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22895. }
  22896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22897. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22898. }
  22899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22900. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22901. }
  22902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22903. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22904. }
  22905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22906. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22907. }
  22908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22909. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22910. }
  22911. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22912. return result;
  22913. };
  22914. VertexData.CreateRibbon = function (options) {
  22915. var pathArray = options.pathArray;
  22916. var closeArray = options.closeArray || false;
  22917. var closePath = options.closePath || false;
  22918. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22919. var offset = options.offset || defaultOffset;
  22920. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22921. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22922. var positions = [];
  22923. var indices = [];
  22924. var normals = [];
  22925. var uvs = [];
  22926. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22927. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22928. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22929. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22930. var minlg; // minimal length among all paths from pathArray
  22931. var lg = []; // array of path lengths : nb of vertex per path
  22932. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22933. var p; // path iterator
  22934. var i; // point iterator
  22935. var j; // point iterator
  22936. // if single path in pathArray
  22937. if (pathArray.length < 2) {
  22938. var ar1 = [];
  22939. var ar2 = [];
  22940. for (i = 0; i < pathArray[0].length - offset; i++) {
  22941. ar1.push(pathArray[0][i]);
  22942. ar2.push(pathArray[0][i + offset]);
  22943. }
  22944. pathArray = [ar1, ar2];
  22945. }
  22946. // positions and horizontal distances (u)
  22947. var idc = 0;
  22948. var closePathCorr = (closePath) ? 1 : 0;
  22949. var path;
  22950. var l;
  22951. minlg = pathArray[0].length;
  22952. var vectlg;
  22953. var dist;
  22954. for (p = 0; p < pathArray.length; p++) {
  22955. uTotalDistance[p] = 0;
  22956. us[p] = [0];
  22957. path = pathArray[p];
  22958. l = path.length;
  22959. minlg = (minlg < l) ? minlg : l;
  22960. j = 0;
  22961. while (j < l) {
  22962. positions.push(path[j].x, path[j].y, path[j].z);
  22963. if (j > 0) {
  22964. vectlg = path[j].subtract(path[j - 1]).length();
  22965. dist = vectlg + uTotalDistance[p];
  22966. us[p].push(dist);
  22967. uTotalDistance[p] = dist;
  22968. }
  22969. j++;
  22970. }
  22971. if (closePath) {
  22972. j--;
  22973. positions.push(path[0].x, path[0].y, path[0].z);
  22974. vectlg = path[j].subtract(path[0]).length();
  22975. dist = vectlg + uTotalDistance[p];
  22976. us[p].push(dist);
  22977. uTotalDistance[p] = dist;
  22978. }
  22979. lg[p] = l + closePathCorr;
  22980. idx[p] = idc;
  22981. idc += (l + closePathCorr);
  22982. }
  22983. // vertical distances (v)
  22984. var path1;
  22985. var path2;
  22986. var vertex1;
  22987. var vertex2;
  22988. for (i = 0; i < minlg + closePathCorr; i++) {
  22989. vTotalDistance[i] = 0;
  22990. vs[i] = [0];
  22991. for (p = 0; p < pathArray.length - 1; p++) {
  22992. path1 = pathArray[p];
  22993. path2 = pathArray[p + 1];
  22994. if (i === minlg) {
  22995. vertex1 = path1[0];
  22996. vertex2 = path2[0];
  22997. }
  22998. else {
  22999. vertex1 = path1[i];
  23000. vertex2 = path2[i];
  23001. }
  23002. vectlg = vertex2.subtract(vertex1).length();
  23003. dist = vectlg + vTotalDistance[i];
  23004. vs[i].push(dist);
  23005. vTotalDistance[i] = dist;
  23006. }
  23007. if (closeArray) {
  23008. path1 = pathArray[p];
  23009. path2 = pathArray[0];
  23010. if (i === minlg) {
  23011. vertex2 = path2[0];
  23012. }
  23013. vectlg = vertex2.subtract(vertex1).length();
  23014. dist = vectlg + vTotalDistance[i];
  23015. vTotalDistance[i] = dist;
  23016. }
  23017. }
  23018. // uvs
  23019. var u;
  23020. var v;
  23021. for (p = 0; p < pathArray.length; p++) {
  23022. for (i = 0; i < minlg + closePathCorr; i++) {
  23023. u = us[p][i] / uTotalDistance[p];
  23024. v = vs[i][p] / vTotalDistance[i];
  23025. uvs.push(u, v);
  23026. }
  23027. }
  23028. // indices
  23029. p = 0; // path index
  23030. var pi = 0; // positions array index
  23031. var l1 = lg[p] - 1; // path1 length
  23032. var l2 = lg[p + 1] - 1; // path2 length
  23033. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23034. var shft = idx[1] - idx[0]; // shift
  23035. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23036. while (pi <= min && p < path1nb) {
  23037. // 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
  23038. indices.push(pi, pi + shft, pi + 1);
  23039. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23040. pi += 1;
  23041. if (pi === min) {
  23042. p++;
  23043. if (p === lg.length - 1) {
  23044. shft = idx[0] - idx[p];
  23045. l1 = lg[p] - 1;
  23046. l2 = lg[0] - 1;
  23047. }
  23048. else {
  23049. shft = idx[p + 1] - idx[p];
  23050. l1 = lg[p] - 1;
  23051. l2 = lg[p + 1] - 1;
  23052. }
  23053. pi = idx[p];
  23054. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23055. }
  23056. }
  23057. // normals
  23058. VertexData.ComputeNormals(positions, indices, normals);
  23059. if (closePath) {
  23060. var indexFirst = 0;
  23061. var indexLast = 0;
  23062. for (p = 0; p < pathArray.length; p++) {
  23063. indexFirst = idx[p] * 3;
  23064. if (p + 1 < pathArray.length) {
  23065. indexLast = (idx[p + 1] - 1) * 3;
  23066. }
  23067. else {
  23068. indexLast = normals.length - 3;
  23069. }
  23070. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23071. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23072. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23073. normals[indexLast] = normals[indexFirst];
  23074. normals[indexLast + 1] = normals[indexFirst + 1];
  23075. normals[indexLast + 2] = normals[indexFirst + 2];
  23076. }
  23077. }
  23078. // sides
  23079. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23080. // Result
  23081. var vertexData = new VertexData();
  23082. vertexData.indices = indices;
  23083. vertexData.positions = positions;
  23084. vertexData.normals = normals;
  23085. vertexData.uvs = uvs;
  23086. if (closePath) {
  23087. vertexData._idx = idx;
  23088. }
  23089. return vertexData;
  23090. };
  23091. VertexData.CreateBox = function (options) {
  23092. var normalsSource = [
  23093. new BABYLON.Vector3(0, 0, 1),
  23094. new BABYLON.Vector3(0, 0, -1),
  23095. new BABYLON.Vector3(1, 0, 0),
  23096. new BABYLON.Vector3(-1, 0, 0),
  23097. new BABYLON.Vector3(0, 1, 0),
  23098. new BABYLON.Vector3(0, -1, 0)
  23099. ];
  23100. var indices = [];
  23101. var positions = [];
  23102. var normals = [];
  23103. var uvs = [];
  23104. var width = options.width || options.size || 1;
  23105. var height = options.height || options.size || 1;
  23106. var depth = options.depth || options.size || 1;
  23107. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23108. var faceUV = options.faceUV || new Array(6);
  23109. var faceColors = options.faceColors;
  23110. var colors = [];
  23111. // default face colors and UV if undefined
  23112. for (var f = 0; f < 6; f++) {
  23113. if (faceUV[f] === undefined) {
  23114. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23115. }
  23116. if (faceColors && faceColors[f] === undefined) {
  23117. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23118. }
  23119. }
  23120. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23121. // Create each face in turn.
  23122. for (var index = 0; index < normalsSource.length; index++) {
  23123. var normal = normalsSource[index];
  23124. // Get two vectors perpendicular to the face normal and to each other.
  23125. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23126. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23127. // Six indices (two triangles) per face.
  23128. var verticesLength = positions.length / 3;
  23129. indices.push(verticesLength);
  23130. indices.push(verticesLength + 1);
  23131. indices.push(verticesLength + 2);
  23132. indices.push(verticesLength);
  23133. indices.push(verticesLength + 2);
  23134. indices.push(verticesLength + 3);
  23135. // Four vertices per face.
  23136. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23137. positions.push(vertex.x, vertex.y, vertex.z);
  23138. normals.push(normal.x, normal.y, normal.z);
  23139. uvs.push(faceUV[index].z, faceUV[index].w);
  23140. if (faceColors) {
  23141. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23142. }
  23143. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23144. positions.push(vertex.x, vertex.y, vertex.z);
  23145. normals.push(normal.x, normal.y, normal.z);
  23146. uvs.push(faceUV[index].x, faceUV[index].w);
  23147. if (faceColors) {
  23148. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23149. }
  23150. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23151. positions.push(vertex.x, vertex.y, vertex.z);
  23152. normals.push(normal.x, normal.y, normal.z);
  23153. uvs.push(faceUV[index].x, faceUV[index].y);
  23154. if (faceColors) {
  23155. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23156. }
  23157. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23158. positions.push(vertex.x, vertex.y, vertex.z);
  23159. normals.push(normal.x, normal.y, normal.z);
  23160. uvs.push(faceUV[index].z, faceUV[index].y);
  23161. if (faceColors) {
  23162. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23163. }
  23164. }
  23165. // sides
  23166. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23167. // Result
  23168. var vertexData = new VertexData();
  23169. vertexData.indices = indices;
  23170. vertexData.positions = positions;
  23171. vertexData.normals = normals;
  23172. vertexData.uvs = uvs;
  23173. if (faceColors) {
  23174. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23175. vertexData.colors = totalColors;
  23176. }
  23177. return vertexData;
  23178. };
  23179. VertexData.CreateSphere = function (options) {
  23180. var segments = options.segments || 32;
  23181. var diameterX = options.diameterX || options.diameter || 1;
  23182. var diameterY = options.diameterY || options.diameter || 1;
  23183. var diameterZ = options.diameterZ || options.diameter || 1;
  23184. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23185. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23187. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23188. var totalZRotationSteps = 2 + segments;
  23189. var totalYRotationSteps = 2 * totalZRotationSteps;
  23190. var indices = [];
  23191. var positions = [];
  23192. var normals = [];
  23193. var uvs = [];
  23194. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23195. var normalizedZ = zRotationStep / totalZRotationSteps;
  23196. var angleZ = normalizedZ * Math.PI * slice;
  23197. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23198. var normalizedY = yRotationStep / totalYRotationSteps;
  23199. var angleY = normalizedY * Math.PI * 2 * arc;
  23200. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23201. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23202. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23203. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23204. var vertex = complete.multiply(radius);
  23205. var normal = complete.divide(radius).normalize();
  23206. positions.push(vertex.x, vertex.y, vertex.z);
  23207. normals.push(normal.x, normal.y, normal.z);
  23208. uvs.push(normalizedY, normalizedZ);
  23209. }
  23210. if (zRotationStep > 0) {
  23211. var verticesCount = positions.length / 3;
  23212. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23213. indices.push((firstIndex));
  23214. indices.push((firstIndex + 1));
  23215. indices.push(firstIndex + totalYRotationSteps + 1);
  23216. indices.push((firstIndex + totalYRotationSteps + 1));
  23217. indices.push((firstIndex + 1));
  23218. indices.push((firstIndex + totalYRotationSteps + 2));
  23219. }
  23220. }
  23221. }
  23222. // Sides
  23223. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23224. // Result
  23225. var vertexData = new VertexData();
  23226. vertexData.indices = indices;
  23227. vertexData.positions = positions;
  23228. vertexData.normals = normals;
  23229. vertexData.uvs = uvs;
  23230. return vertexData;
  23231. };
  23232. // Cylinder and cone
  23233. VertexData.CreateCylinder = function (options) {
  23234. var height = options.height || 2;
  23235. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23236. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23237. var tessellation = options.tessellation || 24;
  23238. var subdivisions = options.subdivisions || 1;
  23239. var hasRings = options.hasRings;
  23240. var enclose = options.enclose;
  23241. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23243. var faceUV = options.faceUV || new Array(3);
  23244. var faceColors = options.faceColors;
  23245. // default face colors and UV if undefined
  23246. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23247. var ringNb = (hasRings) ? subdivisions : 1;
  23248. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23249. var f;
  23250. for (f = 0; f < surfaceNb; f++) {
  23251. if (faceColors && faceColors[f] === undefined) {
  23252. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23253. }
  23254. }
  23255. for (f = 0; f < surfaceNb; f++) {
  23256. if (faceUV && faceUV[f] === undefined) {
  23257. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23258. }
  23259. }
  23260. var indices = [];
  23261. var positions = [];
  23262. var normals = [];
  23263. var uvs = [];
  23264. var colors = [];
  23265. var angle_step = Math.PI * 2 * arc / tessellation;
  23266. var angle;
  23267. var h;
  23268. var radius;
  23269. var tan = (diameterBottom - diameterTop) / 2 / height;
  23270. var ringVertex = BABYLON.Vector3.Zero();
  23271. var ringNormal = BABYLON.Vector3.Zero();
  23272. var ringFirstVertex = BABYLON.Vector3.Zero();
  23273. var ringFirstNormal = BABYLON.Vector3.Zero();
  23274. var quadNormal = BABYLON.Vector3.Zero();
  23275. var Y = BABYLON.Axis.Y;
  23276. // positions, normals, uvs
  23277. var i;
  23278. var j;
  23279. var r;
  23280. var ringIdx = 1;
  23281. var s = 1; // surface index
  23282. var cs = 0;
  23283. var v = 0;
  23284. for (i = 0; i <= subdivisions; i++) {
  23285. h = i / subdivisions;
  23286. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23287. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23288. for (r = 0; r < ringIdx; r++) {
  23289. if (hasRings) {
  23290. s += r;
  23291. }
  23292. if (enclose) {
  23293. s += 2 * r;
  23294. }
  23295. for (j = 0; j <= tessellation; j++) {
  23296. angle = j * angle_step;
  23297. // position
  23298. ringVertex.x = Math.cos(-angle) * radius;
  23299. ringVertex.y = -height / 2 + h * height;
  23300. ringVertex.z = Math.sin(-angle) * radius;
  23301. // normal
  23302. if (diameterTop === 0 && i === subdivisions) {
  23303. // if no top cap, reuse former normals
  23304. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23305. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23306. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23307. }
  23308. else {
  23309. ringNormal.x = ringVertex.x;
  23310. ringNormal.z = ringVertex.z;
  23311. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23312. ringNormal.normalize();
  23313. }
  23314. // keep first ring vertex values for enclose
  23315. if (j === 0) {
  23316. ringFirstVertex.copyFrom(ringVertex);
  23317. ringFirstNormal.copyFrom(ringNormal);
  23318. }
  23319. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23320. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23321. if (hasRings) {
  23322. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23323. }
  23324. else {
  23325. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23326. }
  23327. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23328. if (faceColors) {
  23329. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23330. }
  23331. }
  23332. // if enclose, add four vertices and their dedicated normals
  23333. if (arc !== 1 && enclose) {
  23334. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23335. positions.push(0, ringVertex.y, 0);
  23336. positions.push(0, ringVertex.y, 0);
  23337. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23338. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23339. quadNormal.normalize();
  23340. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23341. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23342. quadNormal.normalize();
  23343. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23344. if (hasRings) {
  23345. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23346. }
  23347. else {
  23348. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23349. }
  23350. uvs.push(faceUV[s + 1].x, v);
  23351. uvs.push(faceUV[s + 1].z, v);
  23352. if (hasRings) {
  23353. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23354. }
  23355. else {
  23356. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23357. }
  23358. uvs.push(faceUV[s + 2].x, v);
  23359. uvs.push(faceUV[s + 2].z, v);
  23360. if (faceColors) {
  23361. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23362. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23363. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23364. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23365. }
  23366. }
  23367. if (cs !== s) {
  23368. cs = s;
  23369. }
  23370. }
  23371. }
  23372. // indices
  23373. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23374. var s;
  23375. i = 0;
  23376. for (s = 0; s < subdivisions; s++) {
  23377. for (j = 0; j < tessellation; j++) {
  23378. var i0 = i * (e + 1) + j;
  23379. var i1 = (i + 1) * (e + 1) + j;
  23380. var i2 = i * (e + 1) + (j + 1);
  23381. var i3 = (i + 1) * (e + 1) + (j + 1);
  23382. indices.push(i0, i1, i2);
  23383. indices.push(i3, i2, i1);
  23384. }
  23385. if (arc !== 1 && enclose) {
  23386. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23387. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23388. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23389. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23390. }
  23391. i = (hasRings) ? (i + 2) : (i + 1);
  23392. }
  23393. // Caps
  23394. var createCylinderCap = function (isTop) {
  23395. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23396. if (radius === 0) {
  23397. return;
  23398. }
  23399. // Cap positions, normals & uvs
  23400. var angle;
  23401. var circleVector;
  23402. var i;
  23403. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23404. var c;
  23405. if (faceColors) {
  23406. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23407. }
  23408. // cap center
  23409. var vbase = positions.length / 3;
  23410. var offset = isTop ? height / 2 : -height / 2;
  23411. var center = new BABYLON.Vector3(0, offset, 0);
  23412. positions.push(center.x, center.y, center.z);
  23413. normals.push(0, isTop ? 1 : -1, 0);
  23414. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23415. if (faceColors) {
  23416. colors.push(c.r, c.g, c.b, c.a);
  23417. }
  23418. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23419. for (i = 0; i <= tessellation; i++) {
  23420. angle = Math.PI * 2 * i * arc / tessellation;
  23421. var cos = Math.cos(-angle);
  23422. var sin = Math.sin(-angle);
  23423. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23424. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23425. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23426. normals.push(0, isTop ? 1 : -1, 0);
  23427. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23428. if (faceColors) {
  23429. colors.push(c.r, c.g, c.b, c.a);
  23430. }
  23431. }
  23432. // Cap indices
  23433. for (i = 0; i < tessellation; i++) {
  23434. if (!isTop) {
  23435. indices.push(vbase);
  23436. indices.push(vbase + (i + 1));
  23437. indices.push(vbase + (i + 2));
  23438. }
  23439. else {
  23440. indices.push(vbase);
  23441. indices.push(vbase + (i + 2));
  23442. indices.push(vbase + (i + 1));
  23443. }
  23444. }
  23445. };
  23446. // add caps to geometry
  23447. createCylinderCap(false);
  23448. createCylinderCap(true);
  23449. // Sides
  23450. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23451. var vertexData = new VertexData();
  23452. vertexData.indices = indices;
  23453. vertexData.positions = positions;
  23454. vertexData.normals = normals;
  23455. vertexData.uvs = uvs;
  23456. if (faceColors) {
  23457. vertexData.colors = colors;
  23458. }
  23459. return vertexData;
  23460. };
  23461. VertexData.CreateTorus = function (options) {
  23462. var indices = [];
  23463. var positions = [];
  23464. var normals = [];
  23465. var uvs = [];
  23466. var diameter = options.diameter || 1;
  23467. var thickness = options.thickness || 0.5;
  23468. var tessellation = options.tessellation || 16;
  23469. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23470. var stride = tessellation + 1;
  23471. for (var i = 0; i <= tessellation; i++) {
  23472. var u = i / tessellation;
  23473. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23474. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23475. for (var j = 0; j <= tessellation; j++) {
  23476. var v = 1 - j / tessellation;
  23477. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23478. var dx = Math.cos(innerAngle);
  23479. var dy = Math.sin(innerAngle);
  23480. // Create a vertex.
  23481. var normal = new BABYLON.Vector3(dx, dy, 0);
  23482. var position = normal.scale(thickness / 2);
  23483. var textureCoordinate = new BABYLON.Vector2(u, v);
  23484. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23485. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23486. positions.push(position.x, position.y, position.z);
  23487. normals.push(normal.x, normal.y, normal.z);
  23488. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23489. // And create indices for two triangles.
  23490. var nextI = (i + 1) % stride;
  23491. var nextJ = (j + 1) % stride;
  23492. indices.push(i * stride + j);
  23493. indices.push(i * stride + nextJ);
  23494. indices.push(nextI * stride + j);
  23495. indices.push(i * stride + nextJ);
  23496. indices.push(nextI * stride + nextJ);
  23497. indices.push(nextI * stride + j);
  23498. }
  23499. }
  23500. // Sides
  23501. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23502. // Result
  23503. var vertexData = new VertexData();
  23504. vertexData.indices = indices;
  23505. vertexData.positions = positions;
  23506. vertexData.normals = normals;
  23507. vertexData.uvs = uvs;
  23508. return vertexData;
  23509. };
  23510. VertexData.CreateLines = function (options) {
  23511. var indices = [];
  23512. var positions = [];
  23513. var points = options.points;
  23514. for (var index = 0; index < points.length; index++) {
  23515. positions.push(points[index].x, points[index].y, points[index].z);
  23516. if (index > 0) {
  23517. indices.push(index - 1);
  23518. indices.push(index);
  23519. }
  23520. }
  23521. // Result
  23522. var vertexData = new VertexData();
  23523. vertexData.indices = indices;
  23524. vertexData.positions = positions;
  23525. return vertexData;
  23526. };
  23527. VertexData.CreateDashedLines = function (options) {
  23528. var dashSize = options.dashSize || 3;
  23529. var gapSize = options.gapSize || 1;
  23530. var dashNb = options.dashNb || 200;
  23531. var points = options.points;
  23532. var positions = new Array();
  23533. var indices = new Array();
  23534. var curvect = BABYLON.Vector3.Zero();
  23535. var lg = 0;
  23536. var nb = 0;
  23537. var shft = 0;
  23538. var dashshft = 0;
  23539. var curshft = 0;
  23540. var idx = 0;
  23541. var i = 0;
  23542. for (i = 0; i < points.length - 1; i++) {
  23543. points[i + 1].subtractToRef(points[i], curvect);
  23544. lg += curvect.length();
  23545. }
  23546. shft = lg / dashNb;
  23547. dashshft = dashSize * shft / (dashSize + gapSize);
  23548. for (i = 0; i < points.length - 1; i++) {
  23549. points[i + 1].subtractToRef(points[i], curvect);
  23550. nb = Math.floor(curvect.length() / shft);
  23551. curvect.normalize();
  23552. for (var j = 0; j < nb; j++) {
  23553. curshft = shft * j;
  23554. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23555. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23556. indices.push(idx, idx + 1);
  23557. idx += 2;
  23558. }
  23559. }
  23560. // Result
  23561. var vertexData = new VertexData();
  23562. vertexData.positions = positions;
  23563. vertexData.indices = indices;
  23564. return vertexData;
  23565. };
  23566. VertexData.CreateGround = function (options) {
  23567. var indices = [];
  23568. var positions = [];
  23569. var normals = [];
  23570. var uvs = [];
  23571. var row, col;
  23572. var width = options.width || 1;
  23573. var height = options.height || 1;
  23574. var subdivisions = options.subdivisions || 1;
  23575. for (row = 0; row <= subdivisions; row++) {
  23576. for (col = 0; col <= subdivisions; col++) {
  23577. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23578. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23579. positions.push(position.x, position.y, position.z);
  23580. normals.push(normal.x, normal.y, normal.z);
  23581. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23582. }
  23583. }
  23584. for (row = 0; row < subdivisions; row++) {
  23585. for (col = 0; col < subdivisions; col++) {
  23586. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23587. indices.push(col + 1 + row * (subdivisions + 1));
  23588. indices.push(col + row * (subdivisions + 1));
  23589. indices.push(col + (row + 1) * (subdivisions + 1));
  23590. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23591. indices.push(col + row * (subdivisions + 1));
  23592. }
  23593. }
  23594. // Result
  23595. var vertexData = new VertexData();
  23596. vertexData.indices = indices;
  23597. vertexData.positions = positions;
  23598. vertexData.normals = normals;
  23599. vertexData.uvs = uvs;
  23600. return vertexData;
  23601. };
  23602. VertexData.CreateTiledGround = function (options) {
  23603. var xmin = options.xmin;
  23604. var zmin = options.zmin;
  23605. var xmax = options.xmax;
  23606. var zmax = options.zmax;
  23607. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23608. var precision = options.precision || { w: 1, h: 1 };
  23609. var indices = [];
  23610. var positions = [];
  23611. var normals = [];
  23612. var uvs = [];
  23613. var row, col, tileRow, tileCol;
  23614. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23615. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23616. precision.w = (precision.w < 1) ? 1 : precision.w;
  23617. precision.h = (precision.h < 1) ? 1 : precision.h;
  23618. var tileSize = {
  23619. 'w': (xmax - xmin) / subdivisions.w,
  23620. 'h': (zmax - zmin) / subdivisions.h
  23621. };
  23622. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23623. // Indices
  23624. var base = positions.length / 3;
  23625. var rowLength = precision.w + 1;
  23626. for (row = 0; row < precision.h; row++) {
  23627. for (col = 0; col < precision.w; col++) {
  23628. var square = [
  23629. base + col + row * rowLength,
  23630. base + (col + 1) + row * rowLength,
  23631. base + (col + 1) + (row + 1) * rowLength,
  23632. base + col + (row + 1) * rowLength
  23633. ];
  23634. indices.push(square[1]);
  23635. indices.push(square[2]);
  23636. indices.push(square[3]);
  23637. indices.push(square[0]);
  23638. indices.push(square[1]);
  23639. indices.push(square[3]);
  23640. }
  23641. }
  23642. // Position, normals and uvs
  23643. var position = BABYLON.Vector3.Zero();
  23644. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23645. for (row = 0; row <= precision.h; row++) {
  23646. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23647. for (col = 0; col <= precision.w; col++) {
  23648. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23649. position.y = 0;
  23650. positions.push(position.x, position.y, position.z);
  23651. normals.push(normal.x, normal.y, normal.z);
  23652. uvs.push(col / precision.w, row / precision.h);
  23653. }
  23654. }
  23655. }
  23656. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23657. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23658. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23659. }
  23660. }
  23661. // Result
  23662. var vertexData = new VertexData();
  23663. vertexData.indices = indices;
  23664. vertexData.positions = positions;
  23665. vertexData.normals = normals;
  23666. vertexData.uvs = uvs;
  23667. return vertexData;
  23668. };
  23669. VertexData.CreateGroundFromHeightMap = function (options) {
  23670. var indices = [];
  23671. var positions = [];
  23672. var normals = [];
  23673. var uvs = [];
  23674. var row, col;
  23675. // Vertices
  23676. for (row = 0; row <= options.subdivisions; row++) {
  23677. for (col = 0; col <= options.subdivisions; col++) {
  23678. 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));
  23679. // Compute height
  23680. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23681. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23682. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23683. var r = options.buffer[pos] / 255.0;
  23684. var g = options.buffer[pos + 1] / 255.0;
  23685. var b = options.buffer[pos + 2] / 255.0;
  23686. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23687. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23688. // Add vertex
  23689. positions.push(position.x, position.y, position.z);
  23690. normals.push(0, 0, 0);
  23691. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23692. }
  23693. }
  23694. // Indices
  23695. for (row = 0; row < options.subdivisions; row++) {
  23696. for (col = 0; col < options.subdivisions; col++) {
  23697. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23698. indices.push(col + 1 + row * (options.subdivisions + 1));
  23699. indices.push(col + row * (options.subdivisions + 1));
  23700. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23701. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23702. indices.push(col + row * (options.subdivisions + 1));
  23703. }
  23704. }
  23705. // Normals
  23706. VertexData.ComputeNormals(positions, indices, normals);
  23707. // Result
  23708. var vertexData = new VertexData();
  23709. vertexData.indices = indices;
  23710. vertexData.positions = positions;
  23711. vertexData.normals = normals;
  23712. vertexData.uvs = uvs;
  23713. return vertexData;
  23714. };
  23715. VertexData.CreatePlane = function (options) {
  23716. var indices = [];
  23717. var positions = [];
  23718. var normals = [];
  23719. var uvs = [];
  23720. var width = options.width || options.size || 1;
  23721. var height = options.height || options.size || 1;
  23722. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23723. // Vertices
  23724. var halfWidth = width / 2.0;
  23725. var halfHeight = height / 2.0;
  23726. positions.push(-halfWidth, -halfHeight, 0);
  23727. normals.push(0, 0, -1.0);
  23728. uvs.push(0.0, 0.0);
  23729. positions.push(halfWidth, -halfHeight, 0);
  23730. normals.push(0, 0, -1.0);
  23731. uvs.push(1.0, 0.0);
  23732. positions.push(halfWidth, halfHeight, 0);
  23733. normals.push(0, 0, -1.0);
  23734. uvs.push(1.0, 1.0);
  23735. positions.push(-halfWidth, halfHeight, 0);
  23736. normals.push(0, 0, -1.0);
  23737. uvs.push(0.0, 1.0);
  23738. // Indices
  23739. indices.push(0);
  23740. indices.push(1);
  23741. indices.push(2);
  23742. indices.push(0);
  23743. indices.push(2);
  23744. indices.push(3);
  23745. // Sides
  23746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23747. // Result
  23748. var vertexData = new VertexData();
  23749. vertexData.indices = indices;
  23750. vertexData.positions = positions;
  23751. vertexData.normals = normals;
  23752. vertexData.uvs = uvs;
  23753. return vertexData;
  23754. };
  23755. VertexData.CreateDisc = function (options) {
  23756. var positions = [];
  23757. var indices = [];
  23758. var normals = [];
  23759. var uvs = [];
  23760. var radius = options.radius || 0.5;
  23761. var tessellation = options.tessellation || 64;
  23762. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23763. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23764. // positions and uvs
  23765. positions.push(0, 0, 0); // disc center first
  23766. uvs.push(0.5, 0.5);
  23767. var theta = Math.PI * 2 * arc;
  23768. var step = theta / tessellation;
  23769. for (var a = 0; a < theta; a += step) {
  23770. var x = Math.cos(a);
  23771. var y = Math.sin(a);
  23772. var u = (x + 1) / 2;
  23773. var v = (1 - y) / 2;
  23774. positions.push(radius * x, radius * y, 0);
  23775. uvs.push(u, v);
  23776. }
  23777. if (arc === 1) {
  23778. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23779. uvs.push(uvs[2], uvs[3]);
  23780. }
  23781. //indices
  23782. var vertexNb = positions.length / 3;
  23783. for (var i = 1; i < vertexNb - 1; i++) {
  23784. indices.push(i + 1, 0, i);
  23785. }
  23786. // result
  23787. VertexData.ComputeNormals(positions, indices, normals);
  23788. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23789. var vertexData = new VertexData();
  23790. vertexData.indices = indices;
  23791. vertexData.positions = positions;
  23792. vertexData.normals = normals;
  23793. vertexData.uvs = uvs;
  23794. return vertexData;
  23795. };
  23796. VertexData.CreateIcoSphere = function (options) {
  23797. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23798. var radius = options.radius || 1;
  23799. var flat = (options.flat === undefined) ? true : options.flat;
  23800. var subdivisions = options.subdivisions || 4;
  23801. var radiusX = options.radiusX || radius;
  23802. var radiusY = options.radiusY || radius;
  23803. var radiusZ = options.radiusZ || radius;
  23804. var t = (1 + Math.sqrt(5)) / 2;
  23805. // 12 vertex x,y,z
  23806. var ico_vertices = [
  23807. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23808. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23809. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23810. ];
  23811. // index of 3 vertex makes a face of icopshere
  23812. var ico_indices = [
  23813. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23814. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23815. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23816. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23817. ];
  23818. // vertex for uv have aliased position, not for UV
  23819. var vertices_unalias_id = [
  23820. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23821. // vertex alias
  23822. 0,
  23823. 2,
  23824. 3,
  23825. 3,
  23826. 3,
  23827. 4,
  23828. 7,
  23829. 8,
  23830. 9,
  23831. 9,
  23832. 10,
  23833. 11 // 23: B + 12
  23834. ];
  23835. // uv as integer step (not pixels !)
  23836. var ico_vertexuv = [
  23837. 5, 1, 3, 1, 6, 4, 0, 0,
  23838. 5, 3, 4, 2, 2, 2, 4, 0,
  23839. 2, 0, 1, 1, 6, 0, 6, 2,
  23840. // vertex alias (for same vertex on different faces)
  23841. 0, 4,
  23842. 3, 3,
  23843. 4, 4,
  23844. 3, 1,
  23845. 4, 2,
  23846. 4, 4,
  23847. 0, 2,
  23848. 1, 1,
  23849. 2, 2,
  23850. 3, 3,
  23851. 1, 3,
  23852. 2, 4 // 23: B + 12
  23853. ];
  23854. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23855. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23856. // First island of uv mapping
  23857. // v = 4h 3+ 2
  23858. // v = 3h 9+ 4
  23859. // v = 2h 9+ 5 B
  23860. // v = 1h 9 1 0
  23861. // v = 0h 3 8 7 A
  23862. // u = 0 1 2 3 4 5 6 *a
  23863. // Second island of uv mapping
  23864. // v = 4h 0+ B+ 4+
  23865. // v = 3h A+ 2+
  23866. // v = 2h 7+ 6 3+
  23867. // v = 1h 8+ 3+
  23868. // v = 0h
  23869. // u = 0 1 2 3 4 5 6 *a
  23870. // Face layout on texture UV mapping
  23871. // ============
  23872. // \ 4 /\ 16 / ======
  23873. // \ / \ / /\ 11 /
  23874. // \/ 7 \/ / \ /
  23875. // ======= / 10 \/
  23876. // /\ 17 /\ =======
  23877. // / \ / \ \ 15 /\
  23878. // / 8 \/ 12 \ \ / \
  23879. // ============ \/ 6 \
  23880. // \ 18 /\ ============
  23881. // \ / \ \ 5 /\ 0 /
  23882. // \/ 13 \ \ / \ /
  23883. // ======= \/ 1 \/
  23884. // =============
  23885. // /\ 19 /\ 2 /\
  23886. // / \ / \ / \
  23887. // / 14 \/ 9 \/ 3 \
  23888. // ===================
  23889. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23890. var ustep = 138 / 1024;
  23891. var vstep = 239 / 1024;
  23892. var uoffset = 60 / 1024;
  23893. var voffset = 26 / 1024;
  23894. // Second island should have margin, not to touch the first island
  23895. // avoid any borderline artefact in pixel rounding
  23896. var island_u_offset = -40 / 1024;
  23897. var island_v_offset = +20 / 1024;
  23898. // face is either island 0 or 1 :
  23899. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23900. var island = [
  23901. 0, 0, 0, 0, 1,
  23902. 0, 0, 1, 1, 0,
  23903. 0, 0, 1, 1, 0,
  23904. 0, 1, 1, 1, 0 // 15 - 19
  23905. ];
  23906. var indices = [];
  23907. var positions = [];
  23908. var normals = [];
  23909. var uvs = [];
  23910. var current_indice = 0;
  23911. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23912. var face_vertex_pos = new Array(3);
  23913. var face_vertex_uv = new Array(3);
  23914. var v012;
  23915. for (v012 = 0; v012 < 3; v012++) {
  23916. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23917. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23918. }
  23919. // create all with normals
  23920. for (var face = 0; face < 20; face++) {
  23921. // 3 vertex per face
  23922. for (v012 = 0; v012 < 3; v012++) {
  23923. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23924. var v_id = ico_indices[3 * face + v012];
  23925. // vertex have 3D position (x,y,z)
  23926. 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]);
  23927. // Normalize to get normal, then scale to radius
  23928. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23929. // uv Coordinates from vertex ID
  23930. 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);
  23931. }
  23932. // Subdivide the face (interpolate pos, norm, uv)
  23933. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23934. // - norm is linear interpolation of vertex corner normal
  23935. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23936. // - uv is linear interpolation
  23937. //
  23938. // Topology is as below for sub-divide by 2
  23939. // vertex shown as v0,v1,v2
  23940. // interp index is i1 to progress in range [v0,v1[
  23941. // interp index is i2 to progress in range [v0,v2[
  23942. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23943. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23944. //
  23945. //
  23946. // i2 v2
  23947. // ^ ^
  23948. // / / \
  23949. // / / \
  23950. // / / \
  23951. // / / (0,1) \
  23952. // / #---------\
  23953. // / / \ (0,0)'/ \
  23954. // / / \ / \
  23955. // / / \ / \
  23956. // / / (0,0) \ / (1,0) \
  23957. // / #---------#---------\
  23958. // v0 v1
  23959. //
  23960. // --------------------> i1
  23961. //
  23962. // interp of (i1,i2):
  23963. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23964. // along i1 : lerp(x0,x1, i1/(S-i2))
  23965. //
  23966. // centroid of triangle is needed to get help normal computation
  23967. // (c1,c2) are used for centroid location
  23968. var interp_vertex = function (i1, i2, c1, c2) {
  23969. // vertex is interpolated from
  23970. // - face_vertex_pos[0..2]
  23971. // - face_vertex_uv[0..2]
  23972. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  23973. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  23974. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  23975. pos_interp.normalize();
  23976. var vertex_normal;
  23977. if (flat) {
  23978. // in flat mode, recalculate normal as face centroid normal
  23979. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  23980. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  23981. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  23982. }
  23983. else {
  23984. // in smooth mode, recalculate normal from each single vertex position
  23985. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  23986. }
  23987. // Vertex normal need correction due to X,Y,Z radius scaling
  23988. vertex_normal.x /= radiusX;
  23989. vertex_normal.y /= radiusY;
  23990. vertex_normal.z /= radiusZ;
  23991. vertex_normal.normalize();
  23992. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  23993. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  23994. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  23995. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  23996. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  23997. uvs.push(uv_interp.x, uv_interp.y);
  23998. // push each vertex has member of a face
  23999. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24000. indices.push(current_indice);
  24001. current_indice++;
  24002. };
  24003. for (var i2 = 0; i2 < subdivisions; i2++) {
  24004. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24005. // face : (i1,i2) for /\ :
  24006. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24007. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24008. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24009. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24010. if (i1 + i2 + 1 < subdivisions) {
  24011. // face : (i1,i2)' for \/ :
  24012. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24013. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24014. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24015. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24016. }
  24017. }
  24018. }
  24019. }
  24020. // Sides
  24021. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24022. // Result
  24023. var vertexData = new VertexData();
  24024. vertexData.indices = indices;
  24025. vertexData.positions = positions;
  24026. vertexData.normals = normals;
  24027. vertexData.uvs = uvs;
  24028. return vertexData;
  24029. };
  24030. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24031. VertexData.CreatePolyhedron = function (options) {
  24032. // provided polyhedron types :
  24033. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24034. // 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)
  24035. var polyhedra = [];
  24036. 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]] };
  24037. 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]] };
  24038. polyhedra[2] = {
  24039. 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]],
  24040. 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]]
  24041. };
  24042. polyhedra[3] = {
  24043. 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]],
  24044. 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]]
  24045. };
  24046. polyhedra[4] = {
  24047. 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]],
  24048. 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]]
  24049. };
  24050. 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]] };
  24051. 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]] };
  24052. 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]] };
  24053. 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]] };
  24054. 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]] };
  24055. 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]] };
  24056. 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]] };
  24057. 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]] };
  24058. 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]] };
  24059. polyhedra[14] = {
  24060. 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]],
  24061. 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]]
  24062. };
  24063. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24064. var size = options.size;
  24065. var sizeX = options.sizeX || size || 1;
  24066. var sizeY = options.sizeY || size || 1;
  24067. var sizeZ = options.sizeZ || size || 1;
  24068. var data = options.custom || polyhedra[type];
  24069. var nbfaces = data.face.length;
  24070. var faceUV = options.faceUV || new Array(nbfaces);
  24071. var faceColors = options.faceColors;
  24072. var flat = (options.flat === undefined) ? true : options.flat;
  24073. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24074. var positions = [];
  24075. var indices = [];
  24076. var normals = [];
  24077. var uvs = [];
  24078. var colors = [];
  24079. var index = 0;
  24080. var faceIdx = 0; // face cursor in the array "indexes"
  24081. var indexes = [];
  24082. var i = 0;
  24083. var f = 0;
  24084. var u, v, ang, x, y, tmp;
  24085. // default face colors and UV if undefined
  24086. if (flat) {
  24087. for (f = 0; f < nbfaces; f++) {
  24088. if (faceColors && faceColors[f] === undefined) {
  24089. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24090. }
  24091. if (faceUV && faceUV[f] === undefined) {
  24092. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24093. }
  24094. }
  24095. }
  24096. if (!flat) {
  24097. for (i = 0; i < data.vertex.length; i++) {
  24098. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24099. uvs.push(0, 0);
  24100. }
  24101. for (f = 0; f < nbfaces; f++) {
  24102. for (i = 0; i < data.face[f].length - 2; i++) {
  24103. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24104. }
  24105. }
  24106. }
  24107. else {
  24108. for (f = 0; f < nbfaces; f++) {
  24109. var fl = data.face[f].length; // number of vertices of the current face
  24110. ang = 2 * Math.PI / fl;
  24111. x = 0.5 * Math.tan(ang / 2);
  24112. y = 0.5;
  24113. // positions, uvs, colors
  24114. for (i = 0; i < fl; i++) {
  24115. // positions
  24116. 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);
  24117. indexes.push(index);
  24118. index++;
  24119. // uvs
  24120. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24121. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24122. uvs.push(u, v);
  24123. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24124. y = x * Math.sin(ang) + y * Math.cos(ang);
  24125. x = tmp;
  24126. // colors
  24127. if (faceColors) {
  24128. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24129. }
  24130. }
  24131. // indices from indexes
  24132. for (i = 0; i < fl - 2; i++) {
  24133. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24134. }
  24135. faceIdx += fl;
  24136. }
  24137. }
  24138. VertexData.ComputeNormals(positions, indices, normals);
  24139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24140. var vertexData = new VertexData();
  24141. vertexData.positions = positions;
  24142. vertexData.indices = indices;
  24143. vertexData.normals = normals;
  24144. vertexData.uvs = uvs;
  24145. if (faceColors && flat) {
  24146. vertexData.colors = colors;
  24147. }
  24148. return vertexData;
  24149. };
  24150. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24151. VertexData.CreateTorusKnot = function (options) {
  24152. var indices = [];
  24153. var positions = [];
  24154. var normals = [];
  24155. var uvs = [];
  24156. var radius = options.radius || 2;
  24157. var tube = options.tube || 0.5;
  24158. var radialSegments = options.radialSegments || 32;
  24159. var tubularSegments = options.tubularSegments || 32;
  24160. var p = options.p || 2;
  24161. var q = options.q || 3;
  24162. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24163. // Helper
  24164. var getPos = function (angle) {
  24165. var cu = Math.cos(angle);
  24166. var su = Math.sin(angle);
  24167. var quOverP = q / p * angle;
  24168. var cs = Math.cos(quOverP);
  24169. var tx = radius * (2 + cs) * 0.5 * cu;
  24170. var ty = radius * (2 + cs) * su * 0.5;
  24171. var tz = radius * Math.sin(quOverP) * 0.5;
  24172. return new BABYLON.Vector3(tx, ty, tz);
  24173. };
  24174. // Vertices
  24175. var i;
  24176. var j;
  24177. for (i = 0; i <= radialSegments; i++) {
  24178. var modI = i % radialSegments;
  24179. var u = modI / radialSegments * 2 * p * Math.PI;
  24180. var p1 = getPos(u);
  24181. var p2 = getPos(u + 0.01);
  24182. var tang = p2.subtract(p1);
  24183. var n = p2.add(p1);
  24184. var bitan = BABYLON.Vector3.Cross(tang, n);
  24185. n = BABYLON.Vector3.Cross(bitan, tang);
  24186. bitan.normalize();
  24187. n.normalize();
  24188. for (j = 0; j < tubularSegments; j++) {
  24189. var modJ = j % tubularSegments;
  24190. var v = modJ / tubularSegments * 2 * Math.PI;
  24191. var cx = -tube * Math.cos(v);
  24192. var cy = tube * Math.sin(v);
  24193. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24194. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24195. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24196. uvs.push(i / radialSegments);
  24197. uvs.push(j / tubularSegments);
  24198. }
  24199. }
  24200. for (i = 0; i < radialSegments; i++) {
  24201. for (j = 0; j < tubularSegments; j++) {
  24202. var jNext = (j + 1) % tubularSegments;
  24203. var a = i * tubularSegments + j;
  24204. var b = (i + 1) * tubularSegments + j;
  24205. var c = (i + 1) * tubularSegments + jNext;
  24206. var d = i * tubularSegments + jNext;
  24207. indices.push(d);
  24208. indices.push(b);
  24209. indices.push(a);
  24210. indices.push(d);
  24211. indices.push(c);
  24212. indices.push(b);
  24213. }
  24214. }
  24215. // Normals
  24216. VertexData.ComputeNormals(positions, indices, normals);
  24217. // Sides
  24218. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24219. // Result
  24220. var vertexData = new VertexData();
  24221. vertexData.indices = indices;
  24222. vertexData.positions = positions;
  24223. vertexData.normals = normals;
  24224. vertexData.uvs = uvs;
  24225. return vertexData;
  24226. };
  24227. // Tools
  24228. /**
  24229. * @param {any} - positions (number[] or Float32Array)
  24230. * @param {any} - indices (number[] or Uint16Array)
  24231. * @param {any} - normals (number[] or Float32Array)
  24232. */
  24233. VertexData.ComputeNormals = function (positions, indices, normals) {
  24234. var index = 0;
  24235. var p1p2x = 0.0;
  24236. var p1p2y = 0.0;
  24237. var p1p2z = 0.0;
  24238. var p3p2x = 0.0;
  24239. var p3p2y = 0.0;
  24240. var p3p2z = 0.0;
  24241. var faceNormalx = 0.0;
  24242. var faceNormaly = 0.0;
  24243. var faceNormalz = 0.0;
  24244. var length = 0.0;
  24245. var i1 = 0;
  24246. var i2 = 0;
  24247. var i3 = 0;
  24248. for (index = 0; index < positions.length; index++) {
  24249. normals[index] = 0.0;
  24250. }
  24251. // indice triplet = 1 face
  24252. var nbFaces = indices.length / 3;
  24253. for (index = 0; index < nbFaces; index++) {
  24254. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24255. i2 = indices[index * 3 + 1];
  24256. i3 = indices[index * 3 + 2];
  24257. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24258. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24259. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24260. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24261. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24262. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24263. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24264. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24265. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24266. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24267. length = (length === 0) ? 1.0 : length;
  24268. faceNormalx /= length; // normalize this normal
  24269. faceNormaly /= length;
  24270. faceNormalz /= length;
  24271. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24272. normals[i1 * 3 + 1] += faceNormaly;
  24273. normals[i1 * 3 + 2] += faceNormalz;
  24274. normals[i2 * 3] += faceNormalx;
  24275. normals[i2 * 3 + 1] += faceNormaly;
  24276. normals[i2 * 3 + 2] += faceNormalz;
  24277. normals[i3 * 3] += faceNormalx;
  24278. normals[i3 * 3 + 1] += faceNormaly;
  24279. normals[i3 * 3 + 2] += faceNormalz;
  24280. }
  24281. // last normalization of each normal
  24282. for (index = 0; index < normals.length / 3; index++) {
  24283. faceNormalx = normals[index * 3];
  24284. faceNormaly = normals[index * 3 + 1];
  24285. faceNormalz = normals[index * 3 + 2];
  24286. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24287. length = (length === 0) ? 1.0 : length;
  24288. faceNormalx /= length;
  24289. faceNormaly /= length;
  24290. faceNormalz /= length;
  24291. normals[index * 3] = faceNormalx;
  24292. normals[index * 3 + 1] = faceNormaly;
  24293. normals[index * 3 + 2] = faceNormalz;
  24294. }
  24295. };
  24296. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24297. var li = indices.length;
  24298. var ln = normals.length;
  24299. var i;
  24300. var n;
  24301. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24302. switch (sideOrientation) {
  24303. case BABYLON.Mesh.FRONTSIDE:
  24304. // nothing changed
  24305. break;
  24306. case BABYLON.Mesh.BACKSIDE:
  24307. var tmp;
  24308. // indices
  24309. for (i = 0; i < li; i += 3) {
  24310. tmp = indices[i];
  24311. indices[i] = indices[i + 2];
  24312. indices[i + 2] = tmp;
  24313. }
  24314. // normals
  24315. for (n = 0; n < ln; n++) {
  24316. normals[n] = -normals[n];
  24317. }
  24318. break;
  24319. case BABYLON.Mesh.DOUBLESIDE:
  24320. // positions
  24321. var lp = positions.length;
  24322. var l = lp / 3;
  24323. for (var p = 0; p < lp; p++) {
  24324. positions[lp + p] = positions[p];
  24325. }
  24326. // indices
  24327. for (i = 0; i < li; i += 3) {
  24328. indices[i + li] = indices[i + 2] + l;
  24329. indices[i + 1 + li] = indices[i + 1] + l;
  24330. indices[i + 2 + li] = indices[i] + l;
  24331. }
  24332. // normals
  24333. for (n = 0; n < ln; n++) {
  24334. normals[ln + n] = -normals[n];
  24335. }
  24336. // uvs
  24337. var lu = uvs.length;
  24338. for (var u = 0; u < lu; u++) {
  24339. uvs[u + lu] = uvs[u];
  24340. }
  24341. break;
  24342. }
  24343. };
  24344. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24345. var vertexData = new VertexData();
  24346. // positions
  24347. var positions = parsedVertexData.positions;
  24348. if (positions) {
  24349. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24350. }
  24351. // normals
  24352. var normals = parsedVertexData.normals;
  24353. if (normals) {
  24354. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24355. }
  24356. // uvs
  24357. var uvs = parsedVertexData.uvs;
  24358. if (uvs) {
  24359. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24360. }
  24361. // uv2s
  24362. var uv2s = parsedVertexData.uv2s;
  24363. if (uv2s) {
  24364. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24365. }
  24366. // uv3s
  24367. var uv3s = parsedVertexData.uv3s;
  24368. if (uv3s) {
  24369. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24370. }
  24371. // uv4s
  24372. var uv4s = parsedVertexData.uv4s;
  24373. if (uv4s) {
  24374. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24375. }
  24376. // uv5s
  24377. var uv5s = parsedVertexData.uv5s;
  24378. if (uv5s) {
  24379. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24380. }
  24381. // uv6s
  24382. var uv6s = parsedVertexData.uv6s;
  24383. if (uv6s) {
  24384. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24385. }
  24386. // colors
  24387. var colors = parsedVertexData.colors;
  24388. if (colors) {
  24389. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24390. }
  24391. // matricesIndices
  24392. var matricesIndices = parsedVertexData.matricesIndices;
  24393. if (matricesIndices) {
  24394. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24395. }
  24396. // matricesWeights
  24397. var matricesWeights = parsedVertexData.matricesWeights;
  24398. if (matricesWeights) {
  24399. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24400. }
  24401. // indices
  24402. var indices = parsedVertexData.indices;
  24403. if (indices) {
  24404. vertexData.indices = indices;
  24405. }
  24406. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24407. };
  24408. return VertexData;
  24409. })();
  24410. BABYLON.VertexData = VertexData;
  24411. })(BABYLON || (BABYLON = {}));
  24412. var BABYLON;
  24413. (function (BABYLON) {
  24414. var Tags = (function () {
  24415. function Tags() {
  24416. }
  24417. Tags.EnableFor = function (obj) {
  24418. obj._tags = obj._tags || {};
  24419. obj.hasTags = function () {
  24420. return Tags.HasTags(obj);
  24421. };
  24422. obj.addTags = function (tagsString) {
  24423. return Tags.AddTagsTo(obj, tagsString);
  24424. };
  24425. obj.removeTags = function (tagsString) {
  24426. return Tags.RemoveTagsFrom(obj, tagsString);
  24427. };
  24428. obj.matchesTagsQuery = function (tagsQuery) {
  24429. return Tags.MatchesQuery(obj, tagsQuery);
  24430. };
  24431. };
  24432. Tags.DisableFor = function (obj) {
  24433. delete obj._tags;
  24434. delete obj.hasTags;
  24435. delete obj.addTags;
  24436. delete obj.removeTags;
  24437. delete obj.matchesTagsQuery;
  24438. };
  24439. Tags.HasTags = function (obj) {
  24440. if (!obj._tags) {
  24441. return false;
  24442. }
  24443. return !BABYLON.Tools.IsEmpty(obj._tags);
  24444. };
  24445. Tags.GetTags = function (obj) {
  24446. if (!obj._tags) {
  24447. return null;
  24448. }
  24449. return obj._tags;
  24450. };
  24451. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24452. // a tag cannot start with '||', '&&', and '!'
  24453. // it cannot contain whitespaces
  24454. Tags.AddTagsTo = function (obj, tagsString) {
  24455. if (!tagsString) {
  24456. return;
  24457. }
  24458. if (typeof tagsString !== "string") {
  24459. return;
  24460. }
  24461. var tags = tagsString.split(" ");
  24462. for (var t in tags) {
  24463. Tags._AddTagTo(obj, tags[t]);
  24464. }
  24465. };
  24466. Tags._AddTagTo = function (obj, tag) {
  24467. tag = tag.trim();
  24468. if (tag === "" || tag === "true" || tag === "false") {
  24469. return;
  24470. }
  24471. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24472. return;
  24473. }
  24474. Tags.EnableFor(obj);
  24475. obj._tags[tag] = true;
  24476. };
  24477. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24478. if (!Tags.HasTags(obj)) {
  24479. return;
  24480. }
  24481. var tags = tagsString.split(" ");
  24482. for (var t in tags) {
  24483. Tags._RemoveTagFrom(obj, tags[t]);
  24484. }
  24485. };
  24486. Tags._RemoveTagFrom = function (obj, tag) {
  24487. delete obj._tags[tag];
  24488. };
  24489. Tags.MatchesQuery = function (obj, tagsQuery) {
  24490. if (tagsQuery === undefined) {
  24491. return true;
  24492. }
  24493. if (tagsQuery === "") {
  24494. return Tags.HasTags(obj);
  24495. }
  24496. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24497. };
  24498. return Tags;
  24499. })();
  24500. BABYLON.Tags = Tags;
  24501. })(BABYLON || (BABYLON = {}));
  24502. var BABYLON;
  24503. (function (BABYLON) {
  24504. var Internals;
  24505. (function (Internals) {
  24506. var AndOrNotEvaluator = (function () {
  24507. function AndOrNotEvaluator() {
  24508. }
  24509. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24510. if (!query.match(/\([^\(\)]*\)/g)) {
  24511. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24512. }
  24513. else {
  24514. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24515. // remove parenthesis
  24516. r = r.slice(1, r.length - 1);
  24517. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24518. });
  24519. }
  24520. if (query === "true") {
  24521. return true;
  24522. }
  24523. if (query === "false") {
  24524. return false;
  24525. }
  24526. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24527. };
  24528. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24529. evaluateCallback = evaluateCallback || (function (r) {
  24530. return r === "true" ? true : false;
  24531. });
  24532. var result;
  24533. var or = parenthesisContent.split("||");
  24534. for (var i in or) {
  24535. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24536. var and = ori.split("&&");
  24537. if (and.length > 1) {
  24538. for (var j = 0; j < and.length; ++j) {
  24539. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24540. if (andj !== "true" && andj !== "false") {
  24541. if (andj[0] === "!") {
  24542. result = !evaluateCallback(andj.substring(1));
  24543. }
  24544. else {
  24545. result = evaluateCallback(andj);
  24546. }
  24547. }
  24548. else {
  24549. result = andj === "true" ? true : false;
  24550. }
  24551. if (!result) {
  24552. ori = "false";
  24553. break;
  24554. }
  24555. }
  24556. }
  24557. if (result || ori === "true") {
  24558. result = true;
  24559. break;
  24560. }
  24561. // result equals false (or undefined)
  24562. if (ori !== "true" && ori !== "false") {
  24563. if (ori[0] === "!") {
  24564. result = !evaluateCallback(ori.substring(1));
  24565. }
  24566. else {
  24567. result = evaluateCallback(ori);
  24568. }
  24569. }
  24570. else {
  24571. result = ori === "true" ? true : false;
  24572. }
  24573. }
  24574. // the whole parenthesis scope is replaced by 'true' or 'false'
  24575. return result ? "true" : "false";
  24576. };
  24577. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24578. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24579. // remove whitespaces
  24580. r = r.replace(/[\s]/g, function () { return ""; });
  24581. return r.length % 2 ? "!" : "";
  24582. });
  24583. booleanString = booleanString.trim();
  24584. if (booleanString === "!true") {
  24585. booleanString = "false";
  24586. }
  24587. else if (booleanString === "!false") {
  24588. booleanString = "true";
  24589. }
  24590. return booleanString;
  24591. };
  24592. return AndOrNotEvaluator;
  24593. })();
  24594. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24595. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24596. })(BABYLON || (BABYLON = {}));
  24597. var BABYLON;
  24598. (function (BABYLON) {
  24599. var PostProcessRenderPass = (function () {
  24600. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24601. this._enabled = true;
  24602. this._refCount = 0;
  24603. this._name = name;
  24604. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24605. this.setRenderList(renderList);
  24606. this._renderTexture.onBeforeRender = beforeRender;
  24607. this._renderTexture.onAfterRender = afterRender;
  24608. this._scene = scene;
  24609. this._renderList = renderList;
  24610. }
  24611. // private
  24612. PostProcessRenderPass.prototype._incRefCount = function () {
  24613. if (this._refCount === 0) {
  24614. this._scene.customRenderTargets.push(this._renderTexture);
  24615. }
  24616. return ++this._refCount;
  24617. };
  24618. PostProcessRenderPass.prototype._decRefCount = function () {
  24619. this._refCount--;
  24620. if (this._refCount <= 0) {
  24621. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24622. }
  24623. return this._refCount;
  24624. };
  24625. PostProcessRenderPass.prototype._update = function () {
  24626. this.setRenderList(this._renderList);
  24627. };
  24628. // public
  24629. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24630. this._renderTexture.renderList = renderList;
  24631. };
  24632. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24633. return this._renderTexture;
  24634. };
  24635. return PostProcessRenderPass;
  24636. })();
  24637. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24638. })(BABYLON || (BABYLON = {}));
  24639. var BABYLON;
  24640. (function (BABYLON) {
  24641. var PostProcessRenderEffect = (function () {
  24642. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24643. this._engine = engine;
  24644. this._name = name;
  24645. this._singleInstance = singleInstance || true;
  24646. this._getPostProcess = getPostProcess;
  24647. this._cameras = [];
  24648. this._indicesForCamera = [];
  24649. this._postProcesses = {};
  24650. this._renderPasses = {};
  24651. this._renderEffectAsPasses = {};
  24652. }
  24653. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24654. get: function () {
  24655. for (var index in this._postProcesses) {
  24656. if (!this._postProcesses[index].isSupported) {
  24657. return false;
  24658. }
  24659. }
  24660. return true;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. PostProcessRenderEffect.prototype._update = function () {
  24666. for (var renderPassName in this._renderPasses) {
  24667. this._renderPasses[renderPassName]._update();
  24668. }
  24669. };
  24670. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24671. this._renderPasses[renderPass._name] = renderPass;
  24672. this._linkParameters();
  24673. };
  24674. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24675. delete this._renderPasses[renderPass._name];
  24676. this._linkParameters();
  24677. };
  24678. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24679. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24680. this._linkParameters();
  24681. };
  24682. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24683. for (var renderPassName in this._renderPasses) {
  24684. if (renderPassName === passName) {
  24685. return this._renderPasses[passName];
  24686. }
  24687. }
  24688. };
  24689. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24690. this._renderPasses = {};
  24691. this._linkParameters();
  24692. };
  24693. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24694. var cameraKey;
  24695. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24696. for (var i = 0; i < _cam.length; i++) {
  24697. var camera = _cam[i];
  24698. var cameraName = camera.name;
  24699. if (this._singleInstance) {
  24700. cameraKey = 0;
  24701. }
  24702. else {
  24703. cameraKey = cameraName;
  24704. }
  24705. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24706. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24707. if (!this._indicesForCamera[cameraName]) {
  24708. this._indicesForCamera[cameraName] = [];
  24709. }
  24710. this._indicesForCamera[cameraName].push(index);
  24711. if (this._cameras.indexOf(camera) === -1) {
  24712. this._cameras[cameraName] = camera;
  24713. }
  24714. for (var passName in this._renderPasses) {
  24715. this._renderPasses[passName]._incRefCount();
  24716. }
  24717. }
  24718. this._linkParameters();
  24719. };
  24720. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24721. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24722. for (var i = 0; i < _cam.length; i++) {
  24723. var camera = _cam[i];
  24724. var cameraName = camera.name;
  24725. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24726. var index = this._cameras.indexOf(cameraName);
  24727. this._indicesForCamera.splice(index, 1);
  24728. this._cameras.splice(index, 1);
  24729. for (var passName in this._renderPasses) {
  24730. this._renderPasses[passName]._decRefCount();
  24731. }
  24732. }
  24733. };
  24734. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24735. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24736. for (var i = 0; i < _cam.length; i++) {
  24737. var camera = _cam[i];
  24738. var cameraName = camera.name;
  24739. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24740. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24741. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24742. }
  24743. }
  24744. for (var passName in this._renderPasses) {
  24745. this._renderPasses[passName]._incRefCount();
  24746. }
  24747. }
  24748. };
  24749. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24750. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24751. for (var i = 0; i < _cam.length; i++) {
  24752. var camera = _cam[i];
  24753. var cameraName = camera.Name;
  24754. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24755. for (var passName in this._renderPasses) {
  24756. this._renderPasses[passName]._decRefCount();
  24757. }
  24758. }
  24759. };
  24760. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24761. if (this._singleInstance) {
  24762. return this._postProcesses[0];
  24763. }
  24764. else {
  24765. return this._postProcesses[camera.name];
  24766. }
  24767. };
  24768. PostProcessRenderEffect.prototype._linkParameters = function () {
  24769. var _this = this;
  24770. for (var index in this._postProcesses) {
  24771. if (this.applyParameters) {
  24772. this.applyParameters(this._postProcesses[index]);
  24773. }
  24774. this._postProcesses[index].onBeforeRender = function (effect) {
  24775. _this._linkTextures(effect);
  24776. };
  24777. }
  24778. };
  24779. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24780. for (var renderPassName in this._renderPasses) {
  24781. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24782. }
  24783. for (var renderEffectName in this._renderEffectAsPasses) {
  24784. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24785. }
  24786. };
  24787. return PostProcessRenderEffect;
  24788. })();
  24789. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24790. })(BABYLON || (BABYLON = {}));
  24791. var BABYLON;
  24792. (function (BABYLON) {
  24793. var PostProcessRenderPipeline = (function () {
  24794. function PostProcessRenderPipeline(engine, name) {
  24795. this._engine = engine;
  24796. this._name = name;
  24797. this._renderEffects = {};
  24798. this._renderEffectsForIsolatedPass = {};
  24799. this._cameras = [];
  24800. }
  24801. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24802. get: function () {
  24803. for (var renderEffectName in this._renderEffects) {
  24804. if (!this._renderEffects[renderEffectName].isSupported) {
  24805. return false;
  24806. }
  24807. }
  24808. return true;
  24809. },
  24810. enumerable: true,
  24811. configurable: true
  24812. });
  24813. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24814. this._renderEffects[renderEffect._name] = renderEffect;
  24815. };
  24816. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24817. var renderEffects = this._renderEffects[renderEffectName];
  24818. if (!renderEffects) {
  24819. return;
  24820. }
  24821. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24822. };
  24823. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24824. var renderEffects = this._renderEffects[renderEffectName];
  24825. if (!renderEffects) {
  24826. return;
  24827. }
  24828. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24829. };
  24830. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24831. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24832. var indicesToDelete = [];
  24833. var i;
  24834. for (i = 0; i < _cam.length; i++) {
  24835. var camera = _cam[i];
  24836. var cameraName = camera.name;
  24837. if (this._cameras.indexOf(camera) === -1) {
  24838. this._cameras[cameraName] = camera;
  24839. }
  24840. else if (unique) {
  24841. indicesToDelete.push(i);
  24842. }
  24843. }
  24844. for (i = 0; i < indicesToDelete.length; i++) {
  24845. cameras.splice(indicesToDelete[i], 1);
  24846. }
  24847. for (var renderEffectName in this._renderEffects) {
  24848. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24849. }
  24850. };
  24851. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24852. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24853. for (var renderEffectName in this._renderEffects) {
  24854. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24855. }
  24856. for (var i = 0; i < _cam.length; i++) {
  24857. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24858. }
  24859. };
  24860. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24861. var _this = this;
  24862. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24863. var pass = null;
  24864. var renderEffectName;
  24865. for (renderEffectName in this._renderEffects) {
  24866. pass = this._renderEffects[renderEffectName].getPass(passName);
  24867. if (pass != null) {
  24868. break;
  24869. }
  24870. }
  24871. if (pass === null) {
  24872. return;
  24873. }
  24874. for (renderEffectName in this._renderEffects) {
  24875. this._renderEffects[renderEffectName]._disable(_cam);
  24876. }
  24877. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24878. for (var i = 0; i < _cam.length; i++) {
  24879. var camera = _cam[i];
  24880. var cameraName = camera.name;
  24881. 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); });
  24882. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24883. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24884. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24885. }
  24886. };
  24887. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24888. var _this = this;
  24889. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24890. for (var i = 0; i < _cam.length; i++) {
  24891. var camera = _cam[i];
  24892. var cameraName = camera.name;
  24893. 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); });
  24894. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24895. }
  24896. for (var renderEffectName in this._renderEffects) {
  24897. this._renderEffects[renderEffectName]._enable(_cam);
  24898. }
  24899. };
  24900. PostProcessRenderPipeline.prototype._update = function () {
  24901. for (var renderEffectName in this._renderEffects) {
  24902. this._renderEffects[renderEffectName]._update();
  24903. }
  24904. for (var i = 0; i < this._cameras.length; i++) {
  24905. var cameraName = this._cameras[i].name;
  24906. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24907. this._renderEffectsForIsolatedPass[cameraName]._update();
  24908. }
  24909. }
  24910. };
  24911. PostProcessRenderPipeline.prototype.dispose = function () {
  24912. // Must be implemented by children
  24913. };
  24914. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24915. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24916. return PostProcessRenderPipeline;
  24917. })();
  24918. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24919. })(BABYLON || (BABYLON = {}));
  24920. var BABYLON;
  24921. (function (BABYLON) {
  24922. var PostProcessRenderPipelineManager = (function () {
  24923. function PostProcessRenderPipelineManager() {
  24924. this._renderPipelines = {};
  24925. }
  24926. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24927. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24928. };
  24929. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24930. var renderPipeline = this._renderPipelines[renderPipelineName];
  24931. if (!renderPipeline) {
  24932. return;
  24933. }
  24934. renderPipeline._attachCameras(cameras, unique);
  24935. };
  24936. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24937. var renderPipeline = this._renderPipelines[renderPipelineName];
  24938. if (!renderPipeline) {
  24939. return;
  24940. }
  24941. renderPipeline._detachCameras(cameras);
  24942. };
  24943. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24944. var renderPipeline = this._renderPipelines[renderPipelineName];
  24945. if (!renderPipeline) {
  24946. return;
  24947. }
  24948. renderPipeline._enableEffect(renderEffectName, cameras);
  24949. };
  24950. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24951. var renderPipeline = this._renderPipelines[renderPipelineName];
  24952. if (!renderPipeline) {
  24953. return;
  24954. }
  24955. renderPipeline._disableEffect(renderEffectName, cameras);
  24956. };
  24957. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24958. var renderPipeline = this._renderPipelines[renderPipelineName];
  24959. if (!renderPipeline) {
  24960. return;
  24961. }
  24962. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24963. };
  24964. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24965. var renderPipeline = this._renderPipelines[renderPipelineName];
  24966. if (!renderPipeline) {
  24967. return;
  24968. }
  24969. renderPipeline._disableDisplayOnlyPass(cameras);
  24970. };
  24971. PostProcessRenderPipelineManager.prototype.update = function () {
  24972. for (var renderPipelineName in this._renderPipelines) {
  24973. var pipeline = this._renderPipelines[renderPipelineName];
  24974. if (!pipeline.isSupported) {
  24975. pipeline.dispose();
  24976. delete this._renderPipelines[renderPipelineName];
  24977. }
  24978. else {
  24979. pipeline._update();
  24980. }
  24981. }
  24982. };
  24983. return PostProcessRenderPipelineManager;
  24984. })();
  24985. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24986. })(BABYLON || (BABYLON = {}));
  24987. var BABYLON;
  24988. (function (BABYLON) {
  24989. var BoundingBoxRenderer = (function () {
  24990. function BoundingBoxRenderer(scene) {
  24991. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24992. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24993. this.showBackLines = true;
  24994. this.renderList = new BABYLON.SmartArray(32);
  24995. this._scene = scene;
  24996. }
  24997. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24998. if (this._colorShader) {
  24999. return;
  25000. }
  25001. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25002. attributes: ["position"],
  25003. uniforms: ["worldViewProjection", "color"]
  25004. });
  25005. var engine = this._scene.getEngine();
  25006. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25007. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25008. 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]);
  25009. };
  25010. BoundingBoxRenderer.prototype.reset = function () {
  25011. this.renderList.reset();
  25012. };
  25013. BoundingBoxRenderer.prototype.render = function () {
  25014. if (this.renderList.length === 0) {
  25015. return;
  25016. }
  25017. this._prepareRessources();
  25018. if (!this._colorShader.isReady()) {
  25019. return;
  25020. }
  25021. var engine = this._scene.getEngine();
  25022. engine.setDepthWrite(false);
  25023. this._colorShader._preBind();
  25024. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25025. var boundingBox = this.renderList.data[boundingBoxIndex];
  25026. var min = boundingBox.minimum;
  25027. var max = boundingBox.maximum;
  25028. var diff = max.subtract(min);
  25029. var median = min.add(diff.scale(0.5));
  25030. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25031. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25032. .multiply(boundingBox.getWorldMatrix());
  25033. // VBOs
  25034. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25035. if (this.showBackLines) {
  25036. // Back
  25037. engine.setDepthFunctionToGreaterOrEqual();
  25038. this._scene.resetCachedMaterial();
  25039. this._colorShader.setColor4("color", this.backColor.toColor4());
  25040. this._colorShader.bind(worldMatrix);
  25041. // Draw order
  25042. engine.draw(false, 0, 24);
  25043. }
  25044. // Front
  25045. engine.setDepthFunctionToLess();
  25046. this._scene.resetCachedMaterial();
  25047. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25048. this._colorShader.bind(worldMatrix);
  25049. // Draw order
  25050. engine.draw(false, 0, 24);
  25051. }
  25052. this._colorShader.unbind();
  25053. engine.setDepthFunctionToLessOrEqual();
  25054. engine.setDepthWrite(true);
  25055. };
  25056. BoundingBoxRenderer.prototype.dispose = function () {
  25057. if (!this._colorShader) {
  25058. return;
  25059. }
  25060. this._colorShader.dispose();
  25061. this._vb.dispose();
  25062. this._scene.getEngine()._releaseBuffer(this._ib);
  25063. };
  25064. return BoundingBoxRenderer;
  25065. })();
  25066. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25067. })(BABYLON || (BABYLON = {}));
  25068. var BABYLON;
  25069. (function (BABYLON) {
  25070. var Condition = (function () {
  25071. function Condition(actionManager) {
  25072. this._actionManager = actionManager;
  25073. }
  25074. Condition.prototype.isValid = function () {
  25075. return true;
  25076. };
  25077. Condition.prototype._getProperty = function (propertyPath) {
  25078. return this._actionManager._getProperty(propertyPath);
  25079. };
  25080. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25081. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25082. };
  25083. return Condition;
  25084. })();
  25085. BABYLON.Condition = Condition;
  25086. var ValueCondition = (function (_super) {
  25087. __extends(ValueCondition, _super);
  25088. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25089. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25090. _super.call(this, actionManager);
  25091. this.propertyPath = propertyPath;
  25092. this.value = value;
  25093. this.operator = operator;
  25094. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25095. this._property = this._getProperty(this.propertyPath);
  25096. }
  25097. Object.defineProperty(ValueCondition, "IsEqual", {
  25098. get: function () {
  25099. return ValueCondition._IsEqual;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(ValueCondition, "IsDifferent", {
  25105. get: function () {
  25106. return ValueCondition._IsDifferent;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. Object.defineProperty(ValueCondition, "IsGreater", {
  25112. get: function () {
  25113. return ValueCondition._IsGreater;
  25114. },
  25115. enumerable: true,
  25116. configurable: true
  25117. });
  25118. Object.defineProperty(ValueCondition, "IsLesser", {
  25119. get: function () {
  25120. return ValueCondition._IsLesser;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. // Methods
  25126. ValueCondition.prototype.isValid = function () {
  25127. switch (this.operator) {
  25128. case ValueCondition.IsGreater:
  25129. return this._target[this._property] > this.value;
  25130. case ValueCondition.IsLesser:
  25131. return this._target[this._property] < this.value;
  25132. case ValueCondition.IsEqual:
  25133. case ValueCondition.IsDifferent:
  25134. var check;
  25135. if (this.value.equals) {
  25136. check = this.value.equals(this._target[this._property]);
  25137. }
  25138. else {
  25139. check = this.value === this._target[this._property];
  25140. }
  25141. return this.operator === ValueCondition.IsEqual ? check : !check;
  25142. }
  25143. return false;
  25144. };
  25145. // Statics
  25146. ValueCondition._IsEqual = 0;
  25147. ValueCondition._IsDifferent = 1;
  25148. ValueCondition._IsGreater = 2;
  25149. ValueCondition._IsLesser = 3;
  25150. return ValueCondition;
  25151. })(Condition);
  25152. BABYLON.ValueCondition = ValueCondition;
  25153. var PredicateCondition = (function (_super) {
  25154. __extends(PredicateCondition, _super);
  25155. function PredicateCondition(actionManager, predicate) {
  25156. _super.call(this, actionManager);
  25157. this.predicate = predicate;
  25158. }
  25159. PredicateCondition.prototype.isValid = function () {
  25160. return this.predicate();
  25161. };
  25162. return PredicateCondition;
  25163. })(Condition);
  25164. BABYLON.PredicateCondition = PredicateCondition;
  25165. var StateCondition = (function (_super) {
  25166. __extends(StateCondition, _super);
  25167. function StateCondition(actionManager, target, value) {
  25168. _super.call(this, actionManager);
  25169. this.value = value;
  25170. this._target = target;
  25171. }
  25172. // Methods
  25173. StateCondition.prototype.isValid = function () {
  25174. return this._target.state === this.value;
  25175. };
  25176. return StateCondition;
  25177. })(Condition);
  25178. BABYLON.StateCondition = StateCondition;
  25179. })(BABYLON || (BABYLON = {}));
  25180. var BABYLON;
  25181. (function (BABYLON) {
  25182. var Action = (function () {
  25183. function Action(triggerOptions, condition) {
  25184. this.triggerOptions = triggerOptions;
  25185. if (triggerOptions.parameter) {
  25186. this.trigger = triggerOptions.trigger;
  25187. this._triggerParameter = triggerOptions.parameter;
  25188. }
  25189. else {
  25190. this.trigger = triggerOptions;
  25191. }
  25192. this._nextActiveAction = this;
  25193. this._condition = condition;
  25194. }
  25195. // Methods
  25196. Action.prototype._prepare = function () {
  25197. };
  25198. Action.prototype.getTriggerParameter = function () {
  25199. return this._triggerParameter;
  25200. };
  25201. Action.prototype._executeCurrent = function (evt) {
  25202. if (this._nextActiveAction._condition) {
  25203. var condition = this._nextActiveAction._condition;
  25204. var currentRenderId = this._actionManager.getScene().getRenderId();
  25205. // We cache the current evaluation for the current frame
  25206. if (condition._evaluationId === currentRenderId) {
  25207. if (!condition._currentResult) {
  25208. return;
  25209. }
  25210. }
  25211. else {
  25212. condition._evaluationId = currentRenderId;
  25213. if (!condition.isValid()) {
  25214. condition._currentResult = false;
  25215. return;
  25216. }
  25217. condition._currentResult = true;
  25218. }
  25219. }
  25220. this._nextActiveAction.execute(evt);
  25221. if (this._nextActiveAction._child) {
  25222. if (!this._nextActiveAction._child._actionManager) {
  25223. this._nextActiveAction._child._actionManager = this._actionManager;
  25224. }
  25225. this._nextActiveAction = this._nextActiveAction._child;
  25226. }
  25227. else {
  25228. this._nextActiveAction = this;
  25229. }
  25230. };
  25231. Action.prototype.execute = function (evt) {
  25232. };
  25233. Action.prototype.then = function (action) {
  25234. this._child = action;
  25235. action._actionManager = this._actionManager;
  25236. action._prepare();
  25237. return action;
  25238. };
  25239. Action.prototype._getProperty = function (propertyPath) {
  25240. return this._actionManager._getProperty(propertyPath);
  25241. };
  25242. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25243. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25244. };
  25245. return Action;
  25246. })();
  25247. BABYLON.Action = Action;
  25248. })(BABYLON || (BABYLON = {}));
  25249. var BABYLON;
  25250. (function (BABYLON) {
  25251. /**
  25252. * ActionEvent is the event beint sent when an action is triggered.
  25253. */
  25254. var ActionEvent = (function () {
  25255. /**
  25256. * @constructor
  25257. * @param source The mesh or sprite that triggered the action.
  25258. * @param pointerX The X mouse cursor position at the time of the event
  25259. * @param pointerY The Y mouse cursor position at the time of the event
  25260. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25261. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25262. */
  25263. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25264. this.source = source;
  25265. this.pointerX = pointerX;
  25266. this.pointerY = pointerY;
  25267. this.meshUnderPointer = meshUnderPointer;
  25268. this.sourceEvent = sourceEvent;
  25269. this.additionalData = additionalData;
  25270. }
  25271. /**
  25272. * Helper function to auto-create an ActionEvent from a source mesh.
  25273. * @param source The source mesh that triggered the event
  25274. * @param evt {Event} The original (browser) event
  25275. */
  25276. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25277. var scene = source.getScene();
  25278. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25279. };
  25280. /**
  25281. * Helper function to auto-create an ActionEvent from a source mesh.
  25282. * @param source The source sprite that triggered the event
  25283. * @param scene Scene associated with the sprite
  25284. * @param evt {Event} The original (browser) event
  25285. */
  25286. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25287. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25288. };
  25289. /**
  25290. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25291. * @param scene the scene where the event occurred
  25292. * @param evt {Event} The original (browser) event
  25293. */
  25294. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25295. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25296. };
  25297. return ActionEvent;
  25298. })();
  25299. BABYLON.ActionEvent = ActionEvent;
  25300. /**
  25301. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25302. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25303. */
  25304. var ActionManager = (function () {
  25305. function ActionManager(scene) {
  25306. // Members
  25307. this.actions = new Array();
  25308. this._scene = scene;
  25309. scene._actionManagers.push(this);
  25310. }
  25311. Object.defineProperty(ActionManager, "NothingTrigger", {
  25312. get: function () {
  25313. return ActionManager._NothingTrigger;
  25314. },
  25315. enumerable: true,
  25316. configurable: true
  25317. });
  25318. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25319. get: function () {
  25320. return ActionManager._OnPickTrigger;
  25321. },
  25322. enumerable: true,
  25323. configurable: true
  25324. });
  25325. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25326. get: function () {
  25327. return ActionManager._OnLeftPickTrigger;
  25328. },
  25329. enumerable: true,
  25330. configurable: true
  25331. });
  25332. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25333. get: function () {
  25334. return ActionManager._OnRightPickTrigger;
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25340. get: function () {
  25341. return ActionManager._OnCenterPickTrigger;
  25342. },
  25343. enumerable: true,
  25344. configurable: true
  25345. });
  25346. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25347. get: function () {
  25348. return ActionManager._OnPointerOverTrigger;
  25349. },
  25350. enumerable: true,
  25351. configurable: true
  25352. });
  25353. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25354. get: function () {
  25355. return ActionManager._OnPointerOutTrigger;
  25356. },
  25357. enumerable: true,
  25358. configurable: true
  25359. });
  25360. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25361. get: function () {
  25362. return ActionManager._OnEveryFrameTrigger;
  25363. },
  25364. enumerable: true,
  25365. configurable: true
  25366. });
  25367. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25368. get: function () {
  25369. return ActionManager._OnIntersectionEnterTrigger;
  25370. },
  25371. enumerable: true,
  25372. configurable: true
  25373. });
  25374. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25375. get: function () {
  25376. return ActionManager._OnIntersectionExitTrigger;
  25377. },
  25378. enumerable: true,
  25379. configurable: true
  25380. });
  25381. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25382. get: function () {
  25383. return ActionManager._OnKeyDownTrigger;
  25384. },
  25385. enumerable: true,
  25386. configurable: true
  25387. });
  25388. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25389. get: function () {
  25390. return ActionManager._OnKeyUpTrigger;
  25391. },
  25392. enumerable: true,
  25393. configurable: true
  25394. });
  25395. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25396. get: function () {
  25397. return ActionManager._OnPickUpTrigger;
  25398. },
  25399. enumerable: true,
  25400. configurable: true
  25401. });
  25402. // Methods
  25403. ActionManager.prototype.dispose = function () {
  25404. var index = this._scene._actionManagers.indexOf(this);
  25405. if (index > -1) {
  25406. this._scene._actionManagers.splice(index, 1);
  25407. }
  25408. };
  25409. ActionManager.prototype.getScene = function () {
  25410. return this._scene;
  25411. };
  25412. /**
  25413. * Does this action manager handles actions of any of the given triggers
  25414. * @param {number[]} triggers - the triggers to be tested
  25415. * @return {boolean} whether one (or more) of the triggers is handeled
  25416. */
  25417. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25418. for (var index = 0; index < this.actions.length; index++) {
  25419. var action = this.actions[index];
  25420. if (triggers.indexOf(action.trigger) > -1) {
  25421. return true;
  25422. }
  25423. }
  25424. return false;
  25425. };
  25426. /**
  25427. * Does this action manager handles actions of a given trigger
  25428. * @param {number} trigger - the trigger to be tested
  25429. * @return {boolean} whether the trigger is handeled
  25430. */
  25431. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25432. for (var index = 0; index < this.actions.length; index++) {
  25433. var action = this.actions[index];
  25434. if (action.trigger === trigger) {
  25435. return true;
  25436. }
  25437. }
  25438. return false;
  25439. };
  25440. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25441. /**
  25442. * Does this action manager has pointer triggers
  25443. * @return {boolean} whether or not it has pointer triggers
  25444. */
  25445. get: function () {
  25446. for (var index = 0; index < this.actions.length; index++) {
  25447. var action = this.actions[index];
  25448. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25449. return true;
  25450. }
  25451. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25452. return true;
  25453. }
  25454. }
  25455. return false;
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25461. /**
  25462. * Does this action manager has pick triggers
  25463. * @return {boolean} whether or not it has pick triggers
  25464. */
  25465. get: function () {
  25466. for (var index = 0; index < this.actions.length; index++) {
  25467. var action = this.actions[index];
  25468. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25469. return true;
  25470. }
  25471. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25472. return true;
  25473. }
  25474. }
  25475. return false;
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. /**
  25481. * Registers an action to this action manager
  25482. * @param {BABYLON.Action} action - the action to be registered
  25483. * @return {BABYLON.Action} the action amended (prepared) after registration
  25484. */
  25485. ActionManager.prototype.registerAction = function (action) {
  25486. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25487. if (this.getScene().actionManager !== this) {
  25488. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25489. return null;
  25490. }
  25491. }
  25492. this.actions.push(action);
  25493. action._actionManager = this;
  25494. action._prepare();
  25495. return action;
  25496. };
  25497. /**
  25498. * Process a specific trigger
  25499. * @param {number} trigger - the trigger to process
  25500. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25501. */
  25502. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25503. for (var index = 0; index < this.actions.length; index++) {
  25504. var action = this.actions[index];
  25505. if (action.trigger === trigger) {
  25506. if (trigger === ActionManager.OnKeyUpTrigger
  25507. || trigger === ActionManager.OnKeyDownTrigger) {
  25508. var parameter = action.getTriggerParameter();
  25509. if (parameter) {
  25510. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25511. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25512. if (actualkey !== parameter.toLowerCase()) {
  25513. continue;
  25514. }
  25515. }
  25516. }
  25517. action._executeCurrent(evt);
  25518. }
  25519. }
  25520. };
  25521. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25522. var properties = propertyPath.split(".");
  25523. for (var index = 0; index < properties.length - 1; index++) {
  25524. target = target[properties[index]];
  25525. }
  25526. return target;
  25527. };
  25528. ActionManager.prototype._getProperty = function (propertyPath) {
  25529. var properties = propertyPath.split(".");
  25530. return properties[properties.length - 1];
  25531. };
  25532. ActionManager.Parse = function (parsedActions, object, scene) {
  25533. var actionManager = new BABYLON.ActionManager(scene);
  25534. if (object === null)
  25535. scene.actionManager = actionManager;
  25536. else
  25537. object.actionManager = actionManager;
  25538. // instanciate a new object
  25539. var instanciate = function (name, params) {
  25540. var newInstance = Object.create(BABYLON[name].prototype);
  25541. newInstance.constructor.apply(newInstance, params);
  25542. return newInstance;
  25543. };
  25544. var parseParameter = function (name, value, target, propertyPath) {
  25545. if (propertyPath === null) {
  25546. // String, boolean or float
  25547. var floatValue = parseFloat(value);
  25548. if (value === "true" || value === "false")
  25549. return value === "true";
  25550. else
  25551. return isNaN(floatValue) ? value : floatValue;
  25552. }
  25553. var effectiveTarget = propertyPath.split(".");
  25554. var values = value.split(",");
  25555. // Get effective Target
  25556. for (var i = 0; i < effectiveTarget.length; i++) {
  25557. target = target[effectiveTarget[i]];
  25558. }
  25559. // Return appropriate value with its type
  25560. if (typeof (target) === "boolean")
  25561. return values[0] === "true";
  25562. if (typeof (target) === "string")
  25563. return values[0];
  25564. // Parameters with multiple values such as Vector3 etc.
  25565. var split = new Array();
  25566. for (var i = 0; i < values.length; i++)
  25567. split.push(parseFloat(values[i]));
  25568. if (target instanceof BABYLON.Vector3)
  25569. return BABYLON.Vector3.FromArray(split);
  25570. if (target instanceof BABYLON.Vector4)
  25571. return BABYLON.Vector4.FromArray(split);
  25572. if (target instanceof BABYLON.Color3)
  25573. return BABYLON.Color3.FromArray(split);
  25574. if (target instanceof BABYLON.Color4)
  25575. return BABYLON.Color4.FromArray(split);
  25576. return parseFloat(values[0]);
  25577. };
  25578. // traverse graph per trigger
  25579. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25580. if (combineArray === void 0) { combineArray = null; }
  25581. if (parsedAction.detached)
  25582. return;
  25583. var parameters = new Array();
  25584. var target = null;
  25585. var propertyPath = null;
  25586. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25587. // Parameters
  25588. if (parsedAction.type === 2)
  25589. parameters.push(actionManager);
  25590. else
  25591. parameters.push(trigger);
  25592. if (combine) {
  25593. var actions = new Array();
  25594. for (var j = 0; j < parsedAction.combine.length; j++) {
  25595. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25596. }
  25597. parameters.push(actions);
  25598. }
  25599. else {
  25600. for (var i = 0; i < parsedAction.properties.length; i++) {
  25601. var value = parsedAction.properties[i].value;
  25602. var name = parsedAction.properties[i].name;
  25603. var targetType = parsedAction.properties[i].targetType;
  25604. if (name === "target")
  25605. if (targetType !== null && targetType === "SceneProperties")
  25606. value = target = scene;
  25607. else
  25608. value = target = scene.getNodeByName(value);
  25609. else if (name === "parent")
  25610. value = scene.getNodeByName(value);
  25611. else if (name === "sound")
  25612. value = scene.getSoundByName(value);
  25613. else if (name !== "propertyPath") {
  25614. if (parsedAction.type === 2 && name === "operator")
  25615. value = BABYLON.ValueCondition[value];
  25616. else
  25617. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25618. }
  25619. else {
  25620. propertyPath = value;
  25621. }
  25622. parameters.push(value);
  25623. }
  25624. }
  25625. if (combineArray === null) {
  25626. parameters.push(condition);
  25627. }
  25628. else {
  25629. parameters.push(null);
  25630. }
  25631. // If interpolate value action
  25632. if (parsedAction.name === "InterpolateValueAction") {
  25633. var param = parameters[parameters.length - 2];
  25634. parameters[parameters.length - 1] = param;
  25635. parameters[parameters.length - 2] = condition;
  25636. }
  25637. // Action or condition(s) and not CombineAction
  25638. var newAction = instanciate(parsedAction.name, parameters);
  25639. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25640. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25641. if (action)
  25642. action.then(nothing);
  25643. else
  25644. actionManager.registerAction(nothing);
  25645. action = nothing;
  25646. }
  25647. if (combineArray === null) {
  25648. if (newAction instanceof BABYLON.Condition) {
  25649. condition = newAction;
  25650. newAction = action;
  25651. }
  25652. else {
  25653. condition = null;
  25654. if (action)
  25655. action.then(newAction);
  25656. else
  25657. actionManager.registerAction(newAction);
  25658. }
  25659. }
  25660. else {
  25661. combineArray.push(newAction);
  25662. }
  25663. for (var i = 0; i < parsedAction.children.length; i++)
  25664. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25665. };
  25666. // triggers
  25667. for (var i = 0; i < parsedActions.children.length; i++) {
  25668. var triggerParams;
  25669. var trigger = parsedActions.children[i];
  25670. if (trigger.properties.length > 0) {
  25671. var param = trigger.properties[0].value;
  25672. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25673. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25674. }
  25675. else
  25676. triggerParams = BABYLON.ActionManager[trigger.name];
  25677. for (var j = 0; j < trigger.children.length; j++) {
  25678. if (!trigger.detached)
  25679. traverse(trigger.children[j], triggerParams, null, null);
  25680. }
  25681. }
  25682. };
  25683. // Statics
  25684. ActionManager._NothingTrigger = 0;
  25685. ActionManager._OnPickTrigger = 1;
  25686. ActionManager._OnLeftPickTrigger = 2;
  25687. ActionManager._OnRightPickTrigger = 3;
  25688. ActionManager._OnCenterPickTrigger = 4;
  25689. ActionManager._OnPointerOverTrigger = 5;
  25690. ActionManager._OnPointerOutTrigger = 6;
  25691. ActionManager._OnEveryFrameTrigger = 7;
  25692. ActionManager._OnIntersectionEnterTrigger = 8;
  25693. ActionManager._OnIntersectionExitTrigger = 9;
  25694. ActionManager._OnKeyDownTrigger = 10;
  25695. ActionManager._OnKeyUpTrigger = 11;
  25696. ActionManager._OnPickUpTrigger = 12;
  25697. return ActionManager;
  25698. })();
  25699. BABYLON.ActionManager = ActionManager;
  25700. })(BABYLON || (BABYLON = {}));
  25701. var BABYLON;
  25702. (function (BABYLON) {
  25703. var InterpolateValueAction = (function (_super) {
  25704. __extends(InterpolateValueAction, _super);
  25705. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25706. if (duration === void 0) { duration = 1000; }
  25707. _super.call(this, triggerOptions, condition);
  25708. this.propertyPath = propertyPath;
  25709. this.value = value;
  25710. this.duration = duration;
  25711. this.stopOtherAnimations = stopOtherAnimations;
  25712. this.onInterpolationDone = onInterpolationDone;
  25713. this._target = target;
  25714. }
  25715. InterpolateValueAction.prototype._prepare = function () {
  25716. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25717. this._property = this._getProperty(this.propertyPath);
  25718. };
  25719. InterpolateValueAction.prototype.execute = function () {
  25720. var scene = this._actionManager.getScene();
  25721. var keys = [
  25722. {
  25723. frame: 0,
  25724. value: this._target[this._property]
  25725. }, {
  25726. frame: 100,
  25727. value: this.value
  25728. }
  25729. ];
  25730. var dataType;
  25731. if (typeof this.value === "number") {
  25732. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25733. }
  25734. else if (this.value instanceof BABYLON.Color3) {
  25735. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25736. }
  25737. else if (this.value instanceof BABYLON.Vector3) {
  25738. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25739. }
  25740. else if (this.value instanceof BABYLON.Matrix) {
  25741. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25742. }
  25743. else if (this.value instanceof BABYLON.Quaternion) {
  25744. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25745. }
  25746. else {
  25747. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25748. return;
  25749. }
  25750. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25751. animation.setKeys(keys);
  25752. if (this.stopOtherAnimations) {
  25753. scene.stopAnimation(this._target);
  25754. }
  25755. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25756. };
  25757. return InterpolateValueAction;
  25758. })(BABYLON.Action);
  25759. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25760. })(BABYLON || (BABYLON = {}));
  25761. var BABYLON;
  25762. (function (BABYLON) {
  25763. var SwitchBooleanAction = (function (_super) {
  25764. __extends(SwitchBooleanAction, _super);
  25765. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25766. _super.call(this, triggerOptions, condition);
  25767. this.propertyPath = propertyPath;
  25768. this._target = target;
  25769. }
  25770. SwitchBooleanAction.prototype._prepare = function () {
  25771. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25772. this._property = this._getProperty(this.propertyPath);
  25773. };
  25774. SwitchBooleanAction.prototype.execute = function () {
  25775. this._target[this._property] = !this._target[this._property];
  25776. };
  25777. return SwitchBooleanAction;
  25778. })(BABYLON.Action);
  25779. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25780. var SetStateAction = (function (_super) {
  25781. __extends(SetStateAction, _super);
  25782. function SetStateAction(triggerOptions, target, value, condition) {
  25783. _super.call(this, triggerOptions, condition);
  25784. this.value = value;
  25785. this._target = target;
  25786. }
  25787. SetStateAction.prototype.execute = function () {
  25788. this._target.state = this.value;
  25789. };
  25790. return SetStateAction;
  25791. })(BABYLON.Action);
  25792. BABYLON.SetStateAction = SetStateAction;
  25793. var SetValueAction = (function (_super) {
  25794. __extends(SetValueAction, _super);
  25795. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25796. _super.call(this, triggerOptions, condition);
  25797. this.propertyPath = propertyPath;
  25798. this.value = value;
  25799. this._target = target;
  25800. }
  25801. SetValueAction.prototype._prepare = function () {
  25802. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25803. this._property = this._getProperty(this.propertyPath);
  25804. };
  25805. SetValueAction.prototype.execute = function () {
  25806. this._target[this._property] = this.value;
  25807. };
  25808. return SetValueAction;
  25809. })(BABYLON.Action);
  25810. BABYLON.SetValueAction = SetValueAction;
  25811. var IncrementValueAction = (function (_super) {
  25812. __extends(IncrementValueAction, _super);
  25813. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25814. _super.call(this, triggerOptions, condition);
  25815. this.propertyPath = propertyPath;
  25816. this.value = value;
  25817. this._target = target;
  25818. }
  25819. IncrementValueAction.prototype._prepare = function () {
  25820. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25821. this._property = this._getProperty(this.propertyPath);
  25822. if (typeof this._target[this._property] !== "number") {
  25823. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25824. }
  25825. };
  25826. IncrementValueAction.prototype.execute = function () {
  25827. this._target[this._property] += this.value;
  25828. };
  25829. return IncrementValueAction;
  25830. })(BABYLON.Action);
  25831. BABYLON.IncrementValueAction = IncrementValueAction;
  25832. var PlayAnimationAction = (function (_super) {
  25833. __extends(PlayAnimationAction, _super);
  25834. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25835. _super.call(this, triggerOptions, condition);
  25836. this.from = from;
  25837. this.to = to;
  25838. this.loop = loop;
  25839. this._target = target;
  25840. }
  25841. PlayAnimationAction.prototype._prepare = function () {
  25842. };
  25843. PlayAnimationAction.prototype.execute = function () {
  25844. var scene = this._actionManager.getScene();
  25845. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25846. };
  25847. return PlayAnimationAction;
  25848. })(BABYLON.Action);
  25849. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25850. var StopAnimationAction = (function (_super) {
  25851. __extends(StopAnimationAction, _super);
  25852. function StopAnimationAction(triggerOptions, target, condition) {
  25853. _super.call(this, triggerOptions, condition);
  25854. this._target = target;
  25855. }
  25856. StopAnimationAction.prototype._prepare = function () {
  25857. };
  25858. StopAnimationAction.prototype.execute = function () {
  25859. var scene = this._actionManager.getScene();
  25860. scene.stopAnimation(this._target);
  25861. };
  25862. return StopAnimationAction;
  25863. })(BABYLON.Action);
  25864. BABYLON.StopAnimationAction = StopAnimationAction;
  25865. var DoNothingAction = (function (_super) {
  25866. __extends(DoNothingAction, _super);
  25867. function DoNothingAction(triggerOptions, condition) {
  25868. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25869. _super.call(this, triggerOptions, condition);
  25870. }
  25871. DoNothingAction.prototype.execute = function () {
  25872. };
  25873. return DoNothingAction;
  25874. })(BABYLON.Action);
  25875. BABYLON.DoNothingAction = DoNothingAction;
  25876. var CombineAction = (function (_super) {
  25877. __extends(CombineAction, _super);
  25878. function CombineAction(triggerOptions, children, condition) {
  25879. _super.call(this, triggerOptions, condition);
  25880. this.children = children;
  25881. }
  25882. CombineAction.prototype._prepare = function () {
  25883. for (var index = 0; index < this.children.length; index++) {
  25884. this.children[index]._actionManager = this._actionManager;
  25885. this.children[index]._prepare();
  25886. }
  25887. };
  25888. CombineAction.prototype.execute = function (evt) {
  25889. for (var index = 0; index < this.children.length; index++) {
  25890. this.children[index].execute(evt);
  25891. }
  25892. };
  25893. return CombineAction;
  25894. })(BABYLON.Action);
  25895. BABYLON.CombineAction = CombineAction;
  25896. var ExecuteCodeAction = (function (_super) {
  25897. __extends(ExecuteCodeAction, _super);
  25898. function ExecuteCodeAction(triggerOptions, func, condition) {
  25899. _super.call(this, triggerOptions, condition);
  25900. this.func = func;
  25901. }
  25902. ExecuteCodeAction.prototype.execute = function (evt) {
  25903. this.func(evt);
  25904. };
  25905. return ExecuteCodeAction;
  25906. })(BABYLON.Action);
  25907. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25908. var SetParentAction = (function (_super) {
  25909. __extends(SetParentAction, _super);
  25910. function SetParentAction(triggerOptions, target, parent, condition) {
  25911. _super.call(this, triggerOptions, condition);
  25912. this._target = target;
  25913. this._parent = parent;
  25914. }
  25915. SetParentAction.prototype._prepare = function () {
  25916. };
  25917. SetParentAction.prototype.execute = function () {
  25918. if (this._target.parent === this._parent) {
  25919. return;
  25920. }
  25921. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25922. invertParentWorldMatrix.invert();
  25923. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25924. this._target.parent = this._parent;
  25925. };
  25926. return SetParentAction;
  25927. })(BABYLON.Action);
  25928. BABYLON.SetParentAction = SetParentAction;
  25929. var PlaySoundAction = (function (_super) {
  25930. __extends(PlaySoundAction, _super);
  25931. function PlaySoundAction(triggerOptions, sound, condition) {
  25932. _super.call(this, triggerOptions, condition);
  25933. this._sound = sound;
  25934. }
  25935. PlaySoundAction.prototype._prepare = function () {
  25936. };
  25937. PlaySoundAction.prototype.execute = function () {
  25938. if (this._sound !== undefined)
  25939. this._sound.play();
  25940. };
  25941. return PlaySoundAction;
  25942. })(BABYLON.Action);
  25943. BABYLON.PlaySoundAction = PlaySoundAction;
  25944. var StopSoundAction = (function (_super) {
  25945. __extends(StopSoundAction, _super);
  25946. function StopSoundAction(triggerOptions, sound, condition) {
  25947. _super.call(this, triggerOptions, condition);
  25948. this._sound = sound;
  25949. }
  25950. StopSoundAction.prototype._prepare = function () {
  25951. };
  25952. StopSoundAction.prototype.execute = function () {
  25953. if (this._sound !== undefined)
  25954. this._sound.stop();
  25955. };
  25956. return StopSoundAction;
  25957. })(BABYLON.Action);
  25958. BABYLON.StopSoundAction = StopSoundAction;
  25959. })(BABYLON || (BABYLON = {}));
  25960. var BABYLON;
  25961. (function (BABYLON) {
  25962. var Geometry = (function () {
  25963. function Geometry(id, scene, vertexData, updatable, mesh) {
  25964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25965. this._totalVertices = 0;
  25966. this._isDisposed = false;
  25967. this.id = id;
  25968. this._engine = scene.getEngine();
  25969. this._meshes = [];
  25970. this._scene = scene;
  25971. //Init vertex buffer cache
  25972. this._vertexBuffers = {};
  25973. this._indices = [];
  25974. // vertexData
  25975. if (vertexData) {
  25976. this.setAllVerticesData(vertexData, updatable);
  25977. }
  25978. else {
  25979. this._totalVertices = 0;
  25980. this._indices = [];
  25981. }
  25982. // applyToMesh
  25983. if (mesh) {
  25984. this.applyToMesh(mesh);
  25985. mesh.computeWorldMatrix(true);
  25986. }
  25987. }
  25988. Object.defineProperty(Geometry.prototype, "extend", {
  25989. get: function () {
  25990. return this._extend;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Geometry.prototype.getScene = function () {
  25996. return this._scene;
  25997. };
  25998. Geometry.prototype.getEngine = function () {
  25999. return this._engine;
  26000. };
  26001. Geometry.prototype.isReady = function () {
  26002. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26003. };
  26004. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26005. vertexData.applyToGeometry(this, updatable);
  26006. this.notifyUpdate();
  26007. };
  26008. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26009. if (this._vertexBuffers[kind]) {
  26010. this._vertexBuffers[kind].dispose();
  26011. }
  26012. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26013. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26014. stride = this._vertexBuffers[kind].getStrideSize();
  26015. this._totalVertices = data.length / stride;
  26016. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26017. var meshes = this._meshes;
  26018. var numOfMeshes = meshes.length;
  26019. for (var index = 0; index < numOfMeshes; index++) {
  26020. var mesh = meshes[index];
  26021. mesh._resetPointsArrayCache();
  26022. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26023. mesh._createGlobalSubMesh();
  26024. mesh.computeWorldMatrix(true);
  26025. }
  26026. }
  26027. this.notifyUpdate(kind);
  26028. };
  26029. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26030. var vertexBuffer = this.getVertexBuffer(kind);
  26031. if (!vertexBuffer) {
  26032. return;
  26033. }
  26034. vertexBuffer.updateDirectly(data, offset);
  26035. this.notifyUpdate(kind);
  26036. };
  26037. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26038. var vertexBuffer = this.getVertexBuffer(kind);
  26039. if (!vertexBuffer) {
  26040. return;
  26041. }
  26042. vertexBuffer.update(data);
  26043. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26044. var stride = vertexBuffer.getStrideSize();
  26045. this._totalVertices = data.length / stride;
  26046. if (updateExtends) {
  26047. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26048. }
  26049. var meshes = this._meshes;
  26050. var numOfMeshes = meshes.length;
  26051. for (var index = 0; index < numOfMeshes; index++) {
  26052. var mesh = meshes[index];
  26053. mesh._resetPointsArrayCache();
  26054. if (updateExtends) {
  26055. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26056. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26057. var subMesh = mesh.subMeshes[subIndex];
  26058. subMesh.refreshBoundingInfo();
  26059. }
  26060. }
  26061. }
  26062. }
  26063. this.notifyUpdate(kind);
  26064. };
  26065. Geometry.prototype.getTotalVertices = function () {
  26066. if (!this.isReady()) {
  26067. return 0;
  26068. }
  26069. return this._totalVertices;
  26070. };
  26071. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26072. var vertexBuffer = this.getVertexBuffer(kind);
  26073. if (!vertexBuffer) {
  26074. return null;
  26075. }
  26076. var orig = vertexBuffer.getData();
  26077. if (!copyWhenShared || this._meshes.length === 1) {
  26078. return orig;
  26079. }
  26080. else {
  26081. var len = orig.length;
  26082. var copy = [];
  26083. for (var i = 0; i < len; i++) {
  26084. copy.push(orig[i]);
  26085. }
  26086. return copy;
  26087. }
  26088. };
  26089. Geometry.prototype.getVertexBuffer = function (kind) {
  26090. if (!this.isReady()) {
  26091. return null;
  26092. }
  26093. return this._vertexBuffers[kind];
  26094. };
  26095. Geometry.prototype.getVertexBuffers = function () {
  26096. if (!this.isReady()) {
  26097. return null;
  26098. }
  26099. return this._vertexBuffers;
  26100. };
  26101. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26102. if (!this._vertexBuffers) {
  26103. if (this._delayInfo) {
  26104. return this._delayInfo.indexOf(kind) !== -1;
  26105. }
  26106. return false;
  26107. }
  26108. return this._vertexBuffers[kind] !== undefined;
  26109. };
  26110. Geometry.prototype.getVerticesDataKinds = function () {
  26111. var result = [];
  26112. var kind;
  26113. if (!this._vertexBuffers && this._delayInfo) {
  26114. for (kind in this._delayInfo) {
  26115. result.push(kind);
  26116. }
  26117. }
  26118. else {
  26119. for (kind in this._vertexBuffers) {
  26120. result.push(kind);
  26121. }
  26122. }
  26123. return result;
  26124. };
  26125. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26126. if (this._indexBuffer) {
  26127. this._engine._releaseBuffer(this._indexBuffer);
  26128. }
  26129. this._indices = indices;
  26130. if (this._meshes.length !== 0 && this._indices) {
  26131. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26132. }
  26133. if (totalVertices !== undefined) {
  26134. this._totalVertices = totalVertices;
  26135. }
  26136. var meshes = this._meshes;
  26137. var numOfMeshes = meshes.length;
  26138. for (var index = 0; index < numOfMeshes; index++) {
  26139. meshes[index]._createGlobalSubMesh();
  26140. }
  26141. this.notifyUpdate();
  26142. };
  26143. Geometry.prototype.getTotalIndices = function () {
  26144. if (!this.isReady()) {
  26145. return 0;
  26146. }
  26147. return this._indices.length;
  26148. };
  26149. Geometry.prototype.getIndices = function (copyWhenShared) {
  26150. if (!this.isReady()) {
  26151. return null;
  26152. }
  26153. var orig = this._indices;
  26154. if (!copyWhenShared || this._meshes.length === 1) {
  26155. return orig;
  26156. }
  26157. else {
  26158. var len = orig.length;
  26159. var copy = [];
  26160. for (var i = 0; i < len; i++) {
  26161. copy.push(orig[i]);
  26162. }
  26163. return copy;
  26164. }
  26165. };
  26166. Geometry.prototype.getIndexBuffer = function () {
  26167. if (!this.isReady()) {
  26168. return null;
  26169. }
  26170. return this._indexBuffer;
  26171. };
  26172. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26173. var meshes = this._meshes;
  26174. var index = meshes.indexOf(mesh);
  26175. if (index === -1) {
  26176. return;
  26177. }
  26178. for (var kind in this._vertexBuffers) {
  26179. this._vertexBuffers[kind].dispose();
  26180. }
  26181. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26182. this._indexBuffer = null;
  26183. }
  26184. meshes.splice(index, 1);
  26185. mesh._geometry = null;
  26186. if (meshes.length === 0 && shouldDispose) {
  26187. this.dispose();
  26188. }
  26189. };
  26190. Geometry.prototype.applyToMesh = function (mesh) {
  26191. if (mesh._geometry === this) {
  26192. return;
  26193. }
  26194. var previousGeometry = mesh._geometry;
  26195. if (previousGeometry) {
  26196. previousGeometry.releaseForMesh(mesh);
  26197. }
  26198. var meshes = this._meshes;
  26199. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26200. mesh._geometry = this;
  26201. this._scene.pushGeometry(this);
  26202. meshes.push(mesh);
  26203. if (this.isReady()) {
  26204. this._applyToMesh(mesh);
  26205. }
  26206. else {
  26207. mesh._boundingInfo = this._boundingInfo;
  26208. }
  26209. };
  26210. Geometry.prototype._applyToMesh = function (mesh) {
  26211. var numOfMeshes = this._meshes.length;
  26212. // vertexBuffers
  26213. for (var kind in this._vertexBuffers) {
  26214. if (numOfMeshes === 1) {
  26215. this._vertexBuffers[kind].create();
  26216. }
  26217. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26218. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26219. mesh._resetPointsArrayCache();
  26220. if (!this._extend) {
  26221. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26222. }
  26223. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26224. mesh._createGlobalSubMesh();
  26225. //bounding info was just created again, world matrix should be applied again.
  26226. mesh._updateBoundingInfo();
  26227. }
  26228. }
  26229. // indexBuffer
  26230. if (numOfMeshes === 1 && this._indices) {
  26231. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26232. }
  26233. if (this._indexBuffer) {
  26234. this._indexBuffer.references = numOfMeshes;
  26235. }
  26236. };
  26237. Geometry.prototype.notifyUpdate = function (kind) {
  26238. if (this.onGeometryUpdated) {
  26239. this.onGeometryUpdated(this, kind);
  26240. }
  26241. };
  26242. Geometry.prototype.load = function (scene, onLoaded) {
  26243. var _this = this;
  26244. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26245. return;
  26246. }
  26247. if (this.isReady()) {
  26248. if (onLoaded) {
  26249. onLoaded();
  26250. }
  26251. return;
  26252. }
  26253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26254. scene._addPendingData(this);
  26255. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26256. _this._delayLoadingFunction(JSON.parse(data), _this);
  26257. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26258. _this._delayInfo = [];
  26259. scene._removePendingData(_this);
  26260. var meshes = _this._meshes;
  26261. var numOfMeshes = meshes.length;
  26262. for (var index = 0; index < numOfMeshes; index++) {
  26263. _this._applyToMesh(meshes[index]);
  26264. }
  26265. if (onLoaded) {
  26266. onLoaded();
  26267. }
  26268. }, function () { }, scene.database);
  26269. };
  26270. Geometry.prototype.isDisposed = function () {
  26271. return this._isDisposed;
  26272. };
  26273. Geometry.prototype.dispose = function () {
  26274. var meshes = this._meshes;
  26275. var numOfMeshes = meshes.length;
  26276. var index;
  26277. for (index = 0; index < numOfMeshes; index++) {
  26278. this.releaseForMesh(meshes[index]);
  26279. }
  26280. this._meshes = [];
  26281. for (var kind in this._vertexBuffers) {
  26282. this._vertexBuffers[kind].dispose();
  26283. }
  26284. this._vertexBuffers = [];
  26285. this._totalVertices = 0;
  26286. if (this._indexBuffer) {
  26287. this._engine._releaseBuffer(this._indexBuffer);
  26288. }
  26289. this._indexBuffer = null;
  26290. this._indices = [];
  26291. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26292. this.delayLoadingFile = null;
  26293. this._delayLoadingFunction = null;
  26294. this._delayInfo = [];
  26295. this._boundingInfo = null;
  26296. this._scene.removeGeometry(this);
  26297. this._isDisposed = true;
  26298. };
  26299. Geometry.prototype.copy = function (id) {
  26300. var vertexData = new BABYLON.VertexData();
  26301. vertexData.indices = [];
  26302. var indices = this.getIndices();
  26303. for (var index = 0; index < indices.length; index++) {
  26304. vertexData.indices.push(indices[index]);
  26305. }
  26306. var updatable = false;
  26307. var stopChecking = false;
  26308. var kind;
  26309. for (kind in this._vertexBuffers) {
  26310. // using slice() to make a copy of the array and not just reference it
  26311. var data = this.getVerticesData(kind);
  26312. if (data instanceof Float32Array) {
  26313. vertexData.set(new Float32Array(data), kind);
  26314. }
  26315. else {
  26316. vertexData.set(data.slice(0), kind);
  26317. }
  26318. if (!stopChecking) {
  26319. updatable = this.getVertexBuffer(kind).isUpdatable();
  26320. stopChecking = !updatable;
  26321. }
  26322. }
  26323. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26324. geometry.delayLoadState = this.delayLoadState;
  26325. geometry.delayLoadingFile = this.delayLoadingFile;
  26326. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26327. for (kind in this._delayInfo) {
  26328. geometry._delayInfo = geometry._delayInfo || [];
  26329. geometry._delayInfo.push(kind);
  26330. }
  26331. // Bounding info
  26332. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26333. return geometry;
  26334. };
  26335. Geometry.prototype.serialize = function () {
  26336. var serializationObject = {};
  26337. serializationObject.id = this.id;
  26338. if (BABYLON.Tags.HasTags(this)) {
  26339. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26340. }
  26341. return serializationObject;
  26342. };
  26343. Geometry.prototype.serializeVerticeData = function () {
  26344. var serializationObject = this.serialize();
  26345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26346. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26347. }
  26348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26349. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26350. }
  26351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26352. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26353. }
  26354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26355. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26356. }
  26357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26358. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26359. }
  26360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26361. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26362. }
  26363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26364. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26365. }
  26366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26367. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26368. }
  26369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26370. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26371. }
  26372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26373. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26374. serializationObject.matricesIndices._isExpanded = true;
  26375. }
  26376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26377. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26378. }
  26379. serializationObject.indices = this.getIndices();
  26380. return serializationObject;
  26381. };
  26382. // Statics
  26383. Geometry.ExtractFromMesh = function (mesh, id) {
  26384. var geometry = mesh._geometry;
  26385. if (!geometry) {
  26386. return null;
  26387. }
  26388. return geometry.copy(id);
  26389. };
  26390. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26391. // be aware Math.random() could cause collisions
  26392. Geometry.RandomId = function () {
  26393. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26394. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26395. return v.toString(16);
  26396. });
  26397. };
  26398. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26399. var scene = mesh.getScene();
  26400. // Geometry
  26401. var geometryId = parsedGeometry.geometryId;
  26402. if (geometryId) {
  26403. var geometry = scene.getGeometryByID(geometryId);
  26404. if (geometry) {
  26405. geometry.applyToMesh(mesh);
  26406. }
  26407. }
  26408. else if (parsedGeometry instanceof ArrayBuffer) {
  26409. var binaryInfo = mesh._binaryInfo;
  26410. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26411. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26412. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26413. }
  26414. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26415. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26416. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26417. }
  26418. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26419. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26420. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26421. }
  26422. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26423. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26424. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26425. }
  26426. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26427. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26428. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26429. }
  26430. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26431. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26432. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26433. }
  26434. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26435. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26436. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26437. }
  26438. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26439. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26440. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26441. }
  26442. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26443. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26444. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26445. }
  26446. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26447. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26448. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26449. }
  26450. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26451. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26453. }
  26454. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26455. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26456. mesh.setIndices(indicesData);
  26457. }
  26458. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26459. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26460. mesh.subMeshes = [];
  26461. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26462. var materialIndex = subMeshesData[(i * 5) + 0];
  26463. var verticesStart = subMeshesData[(i * 5) + 1];
  26464. var verticesCount = subMeshesData[(i * 5) + 2];
  26465. var indexStart = subMeshesData[(i * 5) + 3];
  26466. var indexCount = subMeshesData[(i * 5) + 4];
  26467. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26468. }
  26469. }
  26470. }
  26471. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26472. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26473. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26474. if (parsedGeometry.uvs) {
  26475. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26476. }
  26477. if (parsedGeometry.uvs2) {
  26478. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26479. }
  26480. if (parsedGeometry.uvs3) {
  26481. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26482. }
  26483. if (parsedGeometry.uvs4) {
  26484. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26485. }
  26486. if (parsedGeometry.uvs5) {
  26487. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26488. }
  26489. if (parsedGeometry.uvs6) {
  26490. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26491. }
  26492. if (parsedGeometry.colors) {
  26493. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26494. }
  26495. if (parsedGeometry.matricesIndices) {
  26496. if (!parsedGeometry.matricesIndices._isExpanded) {
  26497. var floatIndices = [];
  26498. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26499. var matricesIndex = parsedGeometry.matricesIndices[i];
  26500. floatIndices.push(matricesIndex & 0x000000FF);
  26501. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26502. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26503. floatIndices.push(matricesIndex >> 24);
  26504. }
  26505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26506. }
  26507. else {
  26508. delete parsedGeometry.matricesIndices._isExpanded;
  26509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26510. }
  26511. }
  26512. if (parsedGeometry.matricesIndicesExtra) {
  26513. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26514. var floatIndices = [];
  26515. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26516. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26517. floatIndices.push(matricesIndex & 0x000000FF);
  26518. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26519. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26520. floatIndices.push(matricesIndex >> 24);
  26521. }
  26522. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26523. }
  26524. else {
  26525. delete parsedGeometry.matricesIndices._isExpanded;
  26526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26527. }
  26528. }
  26529. if (parsedGeometry.matricesWeights) {
  26530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26531. }
  26532. if (parsedGeometry.matricesWeightsExtra) {
  26533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26534. }
  26535. mesh.setIndices(parsedGeometry.indices);
  26536. }
  26537. // SubMeshes
  26538. if (parsedGeometry.subMeshes) {
  26539. mesh.subMeshes = [];
  26540. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26541. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26542. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26543. }
  26544. }
  26545. // Flat shading
  26546. if (mesh._shouldGenerateFlatShading) {
  26547. mesh.convertToFlatShadedMesh();
  26548. delete mesh._shouldGenerateFlatShading;
  26549. }
  26550. // Update
  26551. mesh.computeWorldMatrix(true);
  26552. // Octree
  26553. if (scene['_selectionOctree']) {
  26554. scene['_selectionOctree'].addMesh(mesh);
  26555. }
  26556. };
  26557. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26558. if (scene.getGeometryByID(parsedVertexData.id)) {
  26559. return null; // null since geometry could be something else than a box...
  26560. }
  26561. var geometry = new Geometry(parsedVertexData.id, scene);
  26562. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26563. if (parsedVertexData.delayLoadingFile) {
  26564. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26565. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26566. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26567. geometry._delayInfo = [];
  26568. if (parsedVertexData.hasUVs) {
  26569. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26570. }
  26571. if (parsedVertexData.hasUVs2) {
  26572. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26573. }
  26574. if (parsedVertexData.hasUVs3) {
  26575. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26576. }
  26577. if (parsedVertexData.hasUVs4) {
  26578. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26579. }
  26580. if (parsedVertexData.hasUVs5) {
  26581. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26582. }
  26583. if (parsedVertexData.hasUVs6) {
  26584. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26585. }
  26586. if (parsedVertexData.hasColors) {
  26587. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26588. }
  26589. if (parsedVertexData.hasMatricesIndices) {
  26590. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26591. }
  26592. if (parsedVertexData.hasMatricesWeights) {
  26593. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26594. }
  26595. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26596. }
  26597. else {
  26598. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26599. }
  26600. scene.pushGeometry(geometry, true);
  26601. return geometry;
  26602. };
  26603. return Geometry;
  26604. })();
  26605. BABYLON.Geometry = Geometry;
  26606. /////// Primitives //////////////////////////////////////////////
  26607. var Geometry;
  26608. (function (Geometry) {
  26609. var Primitives;
  26610. (function (Primitives) {
  26611. /// Abstract class
  26612. var _Primitive = (function (_super) {
  26613. __extends(_Primitive, _super);
  26614. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26615. this._beingRegenerated = true;
  26616. this._canBeRegenerated = canBeRegenerated;
  26617. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26618. this._beingRegenerated = false;
  26619. }
  26620. _Primitive.prototype.canBeRegenerated = function () {
  26621. return this._canBeRegenerated;
  26622. };
  26623. _Primitive.prototype.regenerate = function () {
  26624. if (!this._canBeRegenerated) {
  26625. return;
  26626. }
  26627. this._beingRegenerated = true;
  26628. this.setAllVerticesData(this._regenerateVertexData(), false);
  26629. this._beingRegenerated = false;
  26630. };
  26631. _Primitive.prototype.asNewGeometry = function (id) {
  26632. return _super.prototype.copy.call(this, id);
  26633. };
  26634. // overrides
  26635. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26636. if (!this._beingRegenerated) {
  26637. return;
  26638. }
  26639. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26640. };
  26641. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26642. if (!this._beingRegenerated) {
  26643. return;
  26644. }
  26645. _super.prototype.setVerticesData.call(this, kind, data, false);
  26646. };
  26647. // to override
  26648. // protected
  26649. _Primitive.prototype._regenerateVertexData = function () {
  26650. throw new Error("Abstract method");
  26651. };
  26652. _Primitive.prototype.copy = function (id) {
  26653. throw new Error("Must be overriden in sub-classes.");
  26654. };
  26655. _Primitive.prototype.serialize = function () {
  26656. var serializationObject = _super.prototype.serialize.call(this);
  26657. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26658. return serializationObject;
  26659. };
  26660. return _Primitive;
  26661. })(Geometry);
  26662. Primitives._Primitive = _Primitive;
  26663. var Ribbon = (function (_super) {
  26664. __extends(Ribbon, _super);
  26665. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26666. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26667. this.pathArray = pathArray;
  26668. this.closeArray = closeArray;
  26669. this.closePath = closePath;
  26670. this.offset = offset;
  26671. this.side = side;
  26672. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26673. }
  26674. Ribbon.prototype._regenerateVertexData = function () {
  26675. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26676. };
  26677. Ribbon.prototype.copy = function (id) {
  26678. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26679. };
  26680. return Ribbon;
  26681. })(_Primitive);
  26682. Primitives.Ribbon = Ribbon;
  26683. var Box = (function (_super) {
  26684. __extends(Box, _super);
  26685. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26687. this.size = size;
  26688. this.side = side;
  26689. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26690. }
  26691. Box.prototype._regenerateVertexData = function () {
  26692. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26693. };
  26694. Box.prototype.copy = function (id) {
  26695. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26696. };
  26697. Box.prototype.serialize = function () {
  26698. var serializationObject = _super.prototype.serialize.call(this);
  26699. serializationObject.size = this.size;
  26700. return serializationObject;
  26701. };
  26702. Box.Parse = function (parsedBox, scene) {
  26703. if (scene.getGeometryByID(parsedBox.id)) {
  26704. return null; // null since geometry could be something else than a box...
  26705. }
  26706. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26707. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26708. scene.pushGeometry(box, true);
  26709. return box;
  26710. };
  26711. return Box;
  26712. })(_Primitive);
  26713. Primitives.Box = Box;
  26714. var Sphere = (function (_super) {
  26715. __extends(Sphere, _super);
  26716. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26717. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26718. this.segments = segments;
  26719. this.diameter = diameter;
  26720. this.side = side;
  26721. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26722. }
  26723. Sphere.prototype._regenerateVertexData = function () {
  26724. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26725. };
  26726. Sphere.prototype.copy = function (id) {
  26727. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26728. };
  26729. Sphere.prototype.serialize = function () {
  26730. var serializationObject = _super.prototype.serialize.call(this);
  26731. serializationObject.segments = this.segments;
  26732. serializationObject.diameter = this.diameter;
  26733. return serializationObject;
  26734. };
  26735. Sphere.Parse = function (parsedSphere, scene) {
  26736. if (scene.getGeometryByID(parsedSphere.id)) {
  26737. return null; // null since geometry could be something else than a sphere...
  26738. }
  26739. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26740. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26741. scene.pushGeometry(sphere, true);
  26742. return sphere;
  26743. };
  26744. return Sphere;
  26745. })(_Primitive);
  26746. Primitives.Sphere = Sphere;
  26747. var Disc = (function (_super) {
  26748. __extends(Disc, _super);
  26749. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26750. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26751. this.radius = radius;
  26752. this.tessellation = tessellation;
  26753. this.side = side;
  26754. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26755. }
  26756. Disc.prototype._regenerateVertexData = function () {
  26757. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26758. };
  26759. Disc.prototype.copy = function (id) {
  26760. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26761. };
  26762. return Disc;
  26763. })(_Primitive);
  26764. Primitives.Disc = Disc;
  26765. var Cylinder = (function (_super) {
  26766. __extends(Cylinder, _super);
  26767. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26768. if (subdivisions === void 0) { subdivisions = 1; }
  26769. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26770. this.height = height;
  26771. this.diameterTop = diameterTop;
  26772. this.diameterBottom = diameterBottom;
  26773. this.tessellation = tessellation;
  26774. this.subdivisions = subdivisions;
  26775. this.side = side;
  26776. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26777. }
  26778. Cylinder.prototype._regenerateVertexData = function () {
  26779. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26780. };
  26781. Cylinder.prototype.copy = function (id) {
  26782. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26783. };
  26784. Cylinder.prototype.serialize = function () {
  26785. var serializationObject = _super.prototype.serialize.call(this);
  26786. serializationObject.height = this.height;
  26787. serializationObject.diameterTop = this.diameterTop;
  26788. serializationObject.diameterBottom = this.diameterBottom;
  26789. serializationObject.tessellation = this.tessellation;
  26790. return serializationObject;
  26791. };
  26792. Cylinder.Parse = function (parsedCylinder, scene) {
  26793. if (scene.getGeometryByID(parsedCylinder.id)) {
  26794. return null; // null since geometry could be something else than a cylinder...
  26795. }
  26796. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26797. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26798. scene.pushGeometry(cylinder, true);
  26799. return cylinder;
  26800. };
  26801. return Cylinder;
  26802. })(_Primitive);
  26803. Primitives.Cylinder = Cylinder;
  26804. var Torus = (function (_super) {
  26805. __extends(Torus, _super);
  26806. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26807. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26808. this.diameter = diameter;
  26809. this.thickness = thickness;
  26810. this.tessellation = tessellation;
  26811. this.side = side;
  26812. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26813. }
  26814. Torus.prototype._regenerateVertexData = function () {
  26815. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26816. };
  26817. Torus.prototype.copy = function (id) {
  26818. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26819. };
  26820. Torus.prototype.serialize = function () {
  26821. var serializationObject = _super.prototype.serialize.call(this);
  26822. serializationObject.diameter = this.diameter;
  26823. serializationObject.thickness = this.thickness;
  26824. serializationObject.tessellation = this.tessellation;
  26825. return serializationObject;
  26826. };
  26827. Torus.Parse = function (parsedTorus, scene) {
  26828. if (scene.getGeometryByID(parsedTorus.id)) {
  26829. return null; // null since geometry could be something else than a torus...
  26830. }
  26831. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26832. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26833. scene.pushGeometry(torus, true);
  26834. return torus;
  26835. };
  26836. return Torus;
  26837. })(_Primitive);
  26838. Primitives.Torus = Torus;
  26839. var Ground = (function (_super) {
  26840. __extends(Ground, _super);
  26841. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26842. this.width = width;
  26843. this.height = height;
  26844. this.subdivisions = subdivisions;
  26845. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26846. }
  26847. Ground.prototype._regenerateVertexData = function () {
  26848. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26849. };
  26850. Ground.prototype.copy = function (id) {
  26851. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26852. };
  26853. Ground.prototype.serialize = function () {
  26854. var serializationObject = _super.prototype.serialize.call(this);
  26855. serializationObject.width = this.width;
  26856. serializationObject.height = this.height;
  26857. serializationObject.subdivisions = this.subdivisions;
  26858. return serializationObject;
  26859. };
  26860. Ground.Parse = function (parsedGround, scene) {
  26861. if (scene.getGeometryByID(parsedGround.id)) {
  26862. return null; // null since geometry could be something else than a ground...
  26863. }
  26864. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26865. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26866. scene.pushGeometry(ground, true);
  26867. return ground;
  26868. };
  26869. return Ground;
  26870. })(_Primitive);
  26871. Primitives.Ground = Ground;
  26872. var TiledGround = (function (_super) {
  26873. __extends(TiledGround, _super);
  26874. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26875. this.xmin = xmin;
  26876. this.zmin = zmin;
  26877. this.xmax = xmax;
  26878. this.zmax = zmax;
  26879. this.subdivisions = subdivisions;
  26880. this.precision = precision;
  26881. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26882. }
  26883. TiledGround.prototype._regenerateVertexData = function () {
  26884. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26885. };
  26886. TiledGround.prototype.copy = function (id) {
  26887. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26888. };
  26889. return TiledGround;
  26890. })(_Primitive);
  26891. Primitives.TiledGround = TiledGround;
  26892. var Plane = (function (_super) {
  26893. __extends(Plane, _super);
  26894. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26895. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26896. this.size = size;
  26897. this.side = side;
  26898. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26899. }
  26900. Plane.prototype._regenerateVertexData = function () {
  26901. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26902. };
  26903. Plane.prototype.copy = function (id) {
  26904. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26905. };
  26906. Plane.prototype.serialize = function () {
  26907. var serializationObject = _super.prototype.serialize.call(this);
  26908. serializationObject.size = this.size;
  26909. return serializationObject;
  26910. };
  26911. Plane.Parse = function (parsedPlane, scene) {
  26912. if (scene.getGeometryByID(parsedPlane.id)) {
  26913. return null; // null since geometry could be something else than a ground...
  26914. }
  26915. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26916. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26917. scene.pushGeometry(plane, true);
  26918. return plane;
  26919. };
  26920. return Plane;
  26921. })(_Primitive);
  26922. Primitives.Plane = Plane;
  26923. var TorusKnot = (function (_super) {
  26924. __extends(TorusKnot, _super);
  26925. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26926. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26927. this.radius = radius;
  26928. this.tube = tube;
  26929. this.radialSegments = radialSegments;
  26930. this.tubularSegments = tubularSegments;
  26931. this.p = p;
  26932. this.q = q;
  26933. this.side = side;
  26934. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26935. }
  26936. TorusKnot.prototype._regenerateVertexData = function () {
  26937. 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 });
  26938. };
  26939. TorusKnot.prototype.copy = function (id) {
  26940. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26941. };
  26942. TorusKnot.prototype.serialize = function () {
  26943. var serializationObject = _super.prototype.serialize.call(this);
  26944. serializationObject.radius = this.radius;
  26945. serializationObject.tube = this.tube;
  26946. serializationObject.radialSegments = this.radialSegments;
  26947. serializationObject.tubularSegments = this.tubularSegments;
  26948. serializationObject.p = this.p;
  26949. serializationObject.q = this.q;
  26950. return serializationObject;
  26951. };
  26952. ;
  26953. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26954. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26955. return null; // null since geometry could be something else than a ground...
  26956. }
  26957. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26958. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26959. scene.pushGeometry(torusKnot, true);
  26960. return torusKnot;
  26961. };
  26962. return TorusKnot;
  26963. })(_Primitive);
  26964. Primitives.TorusKnot = TorusKnot;
  26965. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26966. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26967. })(BABYLON || (BABYLON = {}));
  26968. var BABYLON;
  26969. (function (BABYLON) {
  26970. var GroundMesh = (function (_super) {
  26971. __extends(GroundMesh, _super);
  26972. function GroundMesh(name, scene) {
  26973. _super.call(this, name, scene);
  26974. this.generateOctree = false;
  26975. this._worldInverse = new BABYLON.Matrix();
  26976. }
  26977. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26978. get: function () {
  26979. return this._subdivisions;
  26980. },
  26981. enumerable: true,
  26982. configurable: true
  26983. });
  26984. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26985. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26986. this._subdivisions = chunksCount;
  26987. this.subdivide(this._subdivisions);
  26988. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26989. };
  26990. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26991. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26992. this.getWorldMatrix().invertToRef(this._worldInverse);
  26993. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26994. var pickInfo = this.intersects(ray);
  26995. if (pickInfo.hit) {
  26996. return pickInfo.pickedPoint.y;
  26997. }
  26998. return 0;
  26999. };
  27000. return GroundMesh;
  27001. })(BABYLON.Mesh);
  27002. BABYLON.GroundMesh = GroundMesh;
  27003. })(BABYLON || (BABYLON = {}));
  27004. var BABYLON;
  27005. (function (BABYLON) {
  27006. var LinesMesh = (function (_super) {
  27007. __extends(LinesMesh, _super);
  27008. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27009. if (parent === void 0) { parent = null; }
  27010. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27011. this.color = new BABYLON.Color3(1, 1, 1);
  27012. this.alpha = 1;
  27013. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27014. attributes: ["position"],
  27015. uniforms: ["worldViewProjection", "color"],
  27016. needAlphaBlending: true
  27017. });
  27018. }
  27019. Object.defineProperty(LinesMesh.prototype, "material", {
  27020. get: function () {
  27021. return this._colorShader;
  27022. },
  27023. enumerable: true,
  27024. configurable: true
  27025. });
  27026. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27027. get: function () {
  27028. return false;
  27029. },
  27030. enumerable: true,
  27031. configurable: true
  27032. });
  27033. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27034. get: function () {
  27035. return false;
  27036. },
  27037. enumerable: true,
  27038. configurable: true
  27039. });
  27040. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27041. var engine = this.getScene().getEngine();
  27042. var indexToBind = this._geometry.getIndexBuffer();
  27043. // VBOs
  27044. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27045. // Color
  27046. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27047. };
  27048. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27049. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27050. return;
  27051. }
  27052. var engine = this.getScene().getEngine();
  27053. // Draw order
  27054. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27055. };
  27056. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27057. return null;
  27058. };
  27059. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27060. this._colorShader.dispose();
  27061. _super.prototype.dispose.call(this, doNotRecurse);
  27062. };
  27063. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27064. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27065. };
  27066. return LinesMesh;
  27067. })(BABYLON.Mesh);
  27068. BABYLON.LinesMesh = LinesMesh;
  27069. })(BABYLON || (BABYLON = {}));
  27070. var BABYLON;
  27071. (function (BABYLON) {
  27072. var DebugLayer = (function () {
  27073. function DebugLayer(scene) {
  27074. var _this = this;
  27075. this._transformationMatrix = BABYLON.Matrix.Identity();
  27076. this._enabled = false;
  27077. this._labelsEnabled = false;
  27078. this._displayStatistics = true;
  27079. this._displayTree = false;
  27080. this._displayLogs = false;
  27081. this._identityMatrix = BABYLON.Matrix.Identity();
  27082. this.axisRatio = 0.02;
  27083. this.accentColor = "orange";
  27084. this._scene = scene;
  27085. this._syncPositions = function () {
  27086. var engine = _this._scene.getEngine();
  27087. var canvasRect = engine.getRenderingCanvasClientRect();
  27088. if (_this._showUI) {
  27089. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27090. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27091. _this._statsDiv.style.width = "400px";
  27092. _this._statsDiv.style.height = "auto";
  27093. _this._statsSubsetDiv.style.maxHeight = "240px";
  27094. _this._optionsDiv.style.left = "0px";
  27095. _this._optionsDiv.style.top = "10px";
  27096. _this._optionsDiv.style.width = "200px";
  27097. _this._optionsDiv.style.height = "auto";
  27098. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27099. _this._logDiv.style.left = "0px";
  27100. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27101. _this._logDiv.style.width = "600px";
  27102. _this._logDiv.style.height = "160px";
  27103. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27104. _this._treeDiv.style.top = "10px";
  27105. _this._treeDiv.style.width = "300px";
  27106. _this._treeDiv.style.height = "auto";
  27107. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27108. }
  27109. _this._globalDiv.style.left = canvasRect.left + "px";
  27110. _this._globalDiv.style.top = canvasRect.top + "px";
  27111. _this._drawingCanvas.style.left = "0px";
  27112. _this._drawingCanvas.style.top = "0px";
  27113. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27114. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27115. var devicePixelRatio = window.devicePixelRatio || 1;
  27116. var context = _this._drawingContext;
  27117. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27118. context.mozBackingStorePixelRatio ||
  27119. context.msBackingStorePixelRatio ||
  27120. context.oBackingStorePixelRatio ||
  27121. context.backingStorePixelRatio || 1;
  27122. _this._ratio = devicePixelRatio / backingStoreRatio;
  27123. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27124. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27125. };
  27126. this._onCanvasClick = function (evt) {
  27127. _this._clickPosition = {
  27128. x: evt.clientX * _this._ratio,
  27129. y: evt.clientY * _this._ratio
  27130. };
  27131. };
  27132. this._syncUI = function () {
  27133. if (_this._showUI) {
  27134. if (_this._displayStatistics) {
  27135. _this._displayStats();
  27136. _this._statsDiv.style.display = "";
  27137. }
  27138. else {
  27139. _this._statsDiv.style.display = "none";
  27140. }
  27141. if (_this._displayLogs) {
  27142. _this._logDiv.style.display = "";
  27143. }
  27144. else {
  27145. _this._logDiv.style.display = "none";
  27146. }
  27147. if (_this._displayTree) {
  27148. _this._treeDiv.style.display = "";
  27149. if (_this._needToRefreshMeshesTree) {
  27150. _this._needToRefreshMeshesTree = false;
  27151. _this._refreshMeshesTreeContent();
  27152. }
  27153. }
  27154. else {
  27155. _this._treeDiv.style.display = "none";
  27156. }
  27157. }
  27158. };
  27159. this._syncData = function () {
  27160. if (_this._labelsEnabled || !_this._showUI) {
  27161. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27162. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27163. var engine = _this._scene.getEngine();
  27164. var viewport = _this._camera.viewport;
  27165. var globalViewport = viewport.toGlobal(engine);
  27166. // Meshes
  27167. var meshes = _this._camera.getActiveMeshes();
  27168. var index;
  27169. var projectedPosition;
  27170. for (index = 0; index < meshes.length; index++) {
  27171. var mesh = meshes.data[index];
  27172. var position = mesh.getBoundingInfo().boundingSphere.center;
  27173. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27174. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27175. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27176. }
  27177. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27178. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27179. }
  27180. }
  27181. // Cameras
  27182. var cameras = _this._scene.cameras;
  27183. for (index = 0; index < cameras.length; index++) {
  27184. var camera = cameras[index];
  27185. if (camera === _this._camera) {
  27186. continue;
  27187. }
  27188. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27189. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27190. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27191. _this._camera.detachControl(engine.getRenderingCanvas());
  27192. _this._camera = camera;
  27193. _this._camera.attachControl(engine.getRenderingCanvas());
  27194. }, function () { return "purple"; });
  27195. }
  27196. }
  27197. // Lights
  27198. var lights = _this._scene.lights;
  27199. for (index = 0; index < lights.length; index++) {
  27200. var light = lights[index];
  27201. if (light.position) {
  27202. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27203. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27204. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27205. light.setEnabled(!light.isEnabled());
  27206. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27207. }
  27208. }
  27209. }
  27210. }
  27211. _this._clickPosition = undefined;
  27212. };
  27213. }
  27214. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27215. while (this._treeSubsetDiv.hasChildNodes()) {
  27216. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27217. }
  27218. // Add meshes
  27219. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27220. sortedArray.sort(function (a, b) {
  27221. if (a.name === b.name) {
  27222. return 0;
  27223. }
  27224. return (a.name > b.name) ? 1 : -1;
  27225. });
  27226. for (var index = 0; index < sortedArray.length; index++) {
  27227. var mesh = sortedArray[index];
  27228. if (!mesh.isEnabled()) {
  27229. continue;
  27230. }
  27231. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27232. m.isVisible = element.checked;
  27233. }, mesh);
  27234. }
  27235. };
  27236. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27237. this._drawingContext.beginPath();
  27238. this._drawingContext.moveTo(zero.x, zero.y);
  27239. this._drawingContext.lineTo(unit.x, unit.y);
  27240. this._drawingContext.strokeStyle = color;
  27241. this._drawingContext.lineWidth = 4;
  27242. this._drawingContext.stroke();
  27243. this._drawingContext.font = "normal 14px Segoe UI";
  27244. this._drawingContext.fillStyle = color;
  27245. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27246. };
  27247. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27248. var position = mesh.getBoundingInfo().boundingSphere.center;
  27249. var worldMatrix = mesh.getWorldMatrix();
  27250. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27251. var unit = (unprojectedVector.subtract(position)).length();
  27252. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27253. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27254. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27255. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27256. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27257. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27258. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27259. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27260. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27261. };
  27262. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27263. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27264. this._drawingContext.font = "normal 12px Segoe UI";
  27265. var textMetrics = this._drawingContext.measureText(text);
  27266. var centerX = projectedPosition.x - textMetrics.width / 2;
  27267. var centerY = projectedPosition.y;
  27268. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27269. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27270. onClick();
  27271. }
  27272. this._drawingContext.beginPath();
  27273. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27274. this._drawingContext.fillStyle = getFillStyle();
  27275. this._drawingContext.globalAlpha = 0.5;
  27276. this._drawingContext.fill();
  27277. this._drawingContext.globalAlpha = 1.0;
  27278. this._drawingContext.strokeStyle = '#FFFFFF';
  27279. this._drawingContext.lineWidth = 1;
  27280. this._drawingContext.stroke();
  27281. this._drawingContext.fillStyle = "#FFFFFF";
  27282. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27283. this._drawingContext.beginPath();
  27284. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27285. this._drawingContext.fill();
  27286. }
  27287. };
  27288. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27289. if (!this._clickPosition) {
  27290. return false;
  27291. }
  27292. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27293. return false;
  27294. }
  27295. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27296. return false;
  27297. }
  27298. return true;
  27299. };
  27300. DebugLayer.prototype.isVisible = function () {
  27301. return this._enabled;
  27302. };
  27303. DebugLayer.prototype.hide = function () {
  27304. if (!this._enabled) {
  27305. return;
  27306. }
  27307. this._enabled = false;
  27308. var engine = this._scene.getEngine();
  27309. this._scene.unregisterBeforeRender(this._syncData);
  27310. this._scene.unregisterAfterRender(this._syncUI);
  27311. this._rootElement.removeChild(this._globalDiv);
  27312. this._scene.forceShowBoundingBoxes = false;
  27313. this._scene.forceWireframe = false;
  27314. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27315. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27316. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27317. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27318. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27319. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27320. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27321. BABYLON.StandardMaterial.LightmapEnabled = true;
  27322. this._scene.shadowsEnabled = true;
  27323. this._scene.particlesEnabled = true;
  27324. this._scene.postProcessesEnabled = true;
  27325. this._scene.collisionsEnabled = true;
  27326. this._scene.lightsEnabled = true;
  27327. this._scene.texturesEnabled = true;
  27328. this._scene.lensFlaresEnabled = true;
  27329. this._scene.proceduralTexturesEnabled = true;
  27330. this._scene.renderTargetsEnabled = true;
  27331. this._scene.probesEnabled = true;
  27332. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27333. };
  27334. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27335. if (showUI === void 0) { showUI = true; }
  27336. if (camera === void 0) { camera = null; }
  27337. if (rootElement === void 0) { rootElement = null; }
  27338. if (this._enabled) {
  27339. return;
  27340. }
  27341. this._enabled = true;
  27342. if (camera) {
  27343. this._camera = camera;
  27344. }
  27345. else {
  27346. this._camera = this._scene.activeCamera;
  27347. }
  27348. this._showUI = showUI;
  27349. var engine = this._scene.getEngine();
  27350. this._globalDiv = document.createElement("div");
  27351. this._rootElement = rootElement || document.body;
  27352. this._rootElement.appendChild(this._globalDiv);
  27353. this._generateDOMelements();
  27354. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27355. this._syncPositions();
  27356. this._scene.registerBeforeRender(this._syncData);
  27357. this._scene.registerAfterRender(this._syncUI);
  27358. };
  27359. DebugLayer.prototype._clearLabels = function () {
  27360. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27361. for (var index = 0; index < this._scene.meshes.length; index++) {
  27362. var mesh = this._scene.meshes[index];
  27363. mesh.renderOverlay = false;
  27364. }
  27365. };
  27366. DebugLayer.prototype._generateheader = function (root, text) {
  27367. var header = document.createElement("div");
  27368. header.innerHTML = text + "&nbsp;";
  27369. header.style.textAlign = "right";
  27370. header.style.width = "100%";
  27371. header.style.color = "white";
  27372. header.style.backgroundColor = "Black";
  27373. header.style.padding = "5px 5px 4px 0px";
  27374. header.style.marginLeft = "-5px";
  27375. header.style.fontWeight = "bold";
  27376. root.appendChild(header);
  27377. };
  27378. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27379. var label = document.createElement("label");
  27380. label.innerHTML = title;
  27381. label.style.color = color;
  27382. root.appendChild(label);
  27383. root.appendChild(document.createElement("br"));
  27384. };
  27385. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27386. if (tag === void 0) { tag = null; }
  27387. var label = document.createElement("label");
  27388. var boundingBoxesCheckbox = document.createElement("input");
  27389. boundingBoxesCheckbox.type = "checkbox";
  27390. boundingBoxesCheckbox.checked = initialState;
  27391. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27392. task(evt.target, tag);
  27393. });
  27394. label.appendChild(boundingBoxesCheckbox);
  27395. var container = document.createElement("span");
  27396. var leftPart = document.createElement("span");
  27397. var rightPart = document.createElement("span");
  27398. rightPart.style.cssFloat = "right";
  27399. leftPart.innerHTML = leftTitle;
  27400. rightPart.innerHTML = rightTitle;
  27401. rightPart.style.fontSize = "12px";
  27402. rightPart.style.maxWidth = "200px";
  27403. container.appendChild(leftPart);
  27404. container.appendChild(rightPart);
  27405. label.appendChild(container);
  27406. root.appendChild(label);
  27407. root.appendChild(document.createElement("br"));
  27408. };
  27409. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27410. if (tag === void 0) { tag = null; }
  27411. var label = document.createElement("label");
  27412. var checkBox = document.createElement("input");
  27413. checkBox.type = "checkbox";
  27414. checkBox.checked = initialState;
  27415. checkBox.addEventListener("change", function (evt) {
  27416. task(evt.target, tag);
  27417. });
  27418. label.appendChild(checkBox);
  27419. label.appendChild(document.createTextNode(title));
  27420. root.appendChild(label);
  27421. root.appendChild(document.createElement("br"));
  27422. };
  27423. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27424. if (tag === void 0) { tag = null; }
  27425. var button = document.createElement("button");
  27426. button.innerHTML = title;
  27427. button.style.height = "24px";
  27428. button.style.width = "150px";
  27429. button.style.marginBottom = "5px";
  27430. button.style.color = "#444444";
  27431. button.style.border = "1px solid white";
  27432. button.className = "debugLayerButton";
  27433. button.addEventListener("click", function (evt) {
  27434. task(evt.target, tag);
  27435. });
  27436. root.appendChild(button);
  27437. root.appendChild(document.createElement("br"));
  27438. };
  27439. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27440. if (tag === void 0) { tag = null; }
  27441. var label = document.createElement("label");
  27442. var boundingBoxesRadio = document.createElement("input");
  27443. boundingBoxesRadio.type = "radio";
  27444. boundingBoxesRadio.name = name;
  27445. boundingBoxesRadio.checked = initialState;
  27446. boundingBoxesRadio.addEventListener("change", function (evt) {
  27447. task(evt.target, tag);
  27448. });
  27449. label.appendChild(boundingBoxesRadio);
  27450. label.appendChild(document.createTextNode(title));
  27451. root.appendChild(label);
  27452. root.appendChild(document.createElement("br"));
  27453. };
  27454. DebugLayer.prototype._generateDOMelements = function () {
  27455. var _this = this;
  27456. this._globalDiv.id = "DebugLayer";
  27457. this._globalDiv.style.position = "absolute";
  27458. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27459. this._globalDiv.style.fontSize = "14px";
  27460. this._globalDiv.style.color = "white";
  27461. // Drawing canvas
  27462. this._drawingCanvas = document.createElement("canvas");
  27463. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27464. this._drawingCanvas.style.position = "absolute";
  27465. this._drawingCanvas.style.pointerEvents = "none";
  27466. this._drawingCanvas.style.backgroundColor = "transparent";
  27467. this._drawingContext = this._drawingCanvas.getContext("2d");
  27468. this._globalDiv.appendChild(this._drawingCanvas);
  27469. if (this._showUI) {
  27470. var background = "rgba(128, 128, 128, 0.4)";
  27471. var border = "rgb(180, 180, 180) solid 1px";
  27472. // Stats
  27473. this._statsDiv = document.createElement("div");
  27474. this._statsDiv.id = "DebugLayerStats";
  27475. this._statsDiv.style.border = border;
  27476. this._statsDiv.style.position = "absolute";
  27477. this._statsDiv.style.background = background;
  27478. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27479. this._generateheader(this._statsDiv, "STATISTICS");
  27480. this._statsSubsetDiv = document.createElement("div");
  27481. this._statsSubsetDiv.style.paddingTop = "5px";
  27482. this._statsSubsetDiv.style.paddingBottom = "5px";
  27483. this._statsSubsetDiv.style.overflowY = "auto";
  27484. this._statsDiv.appendChild(this._statsSubsetDiv);
  27485. // Tree
  27486. this._treeDiv = document.createElement("div");
  27487. this._treeDiv.id = "DebugLayerTree";
  27488. this._treeDiv.style.border = border;
  27489. this._treeDiv.style.position = "absolute";
  27490. this._treeDiv.style.background = background;
  27491. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27492. this._treeDiv.style.display = "none";
  27493. this._generateheader(this._treeDiv, "MESHES TREE");
  27494. this._treeSubsetDiv = document.createElement("div");
  27495. this._treeSubsetDiv.style.paddingTop = "5px";
  27496. this._treeSubsetDiv.style.paddingRight = "5px";
  27497. this._treeSubsetDiv.style.overflowY = "auto";
  27498. this._treeSubsetDiv.style.maxHeight = "300px";
  27499. this._treeDiv.appendChild(this._treeSubsetDiv);
  27500. this._needToRefreshMeshesTree = true;
  27501. // Logs
  27502. this._logDiv = document.createElement("div");
  27503. this._logDiv.style.border = border;
  27504. this._logDiv.id = "DebugLayerLogs";
  27505. this._logDiv.style.position = "absolute";
  27506. this._logDiv.style.background = background;
  27507. this._logDiv.style.padding = "0px 0px 0px 5px";
  27508. this._logDiv.style.display = "none";
  27509. this._generateheader(this._logDiv, "LOGS");
  27510. this._logSubsetDiv = document.createElement("div");
  27511. this._logSubsetDiv.style.height = "127px";
  27512. this._logSubsetDiv.style.paddingTop = "5px";
  27513. this._logSubsetDiv.style.overflowY = "auto";
  27514. this._logSubsetDiv.style.fontSize = "12px";
  27515. this._logSubsetDiv.style.fontFamily = "consolas";
  27516. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27517. this._logDiv.appendChild(this._logSubsetDiv);
  27518. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27519. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27520. };
  27521. // Options
  27522. this._optionsDiv = document.createElement("div");
  27523. this._optionsDiv.id = "DebugLayerOptions";
  27524. this._optionsDiv.style.border = border;
  27525. this._optionsDiv.style.position = "absolute";
  27526. this._optionsDiv.style.background = background;
  27527. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27528. this._optionsDiv.style.overflowY = "auto";
  27529. this._generateheader(this._optionsDiv, "OPTIONS");
  27530. this._optionsSubsetDiv = document.createElement("div");
  27531. this._optionsSubsetDiv.style.paddingTop = "5px";
  27532. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27533. this._optionsSubsetDiv.style.overflowY = "auto";
  27534. this._optionsSubsetDiv.style.maxHeight = "200px";
  27535. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27536. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27537. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27538. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27539. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27540. _this._displayTree = element.checked;
  27541. _this._needToRefreshMeshesTree = true;
  27542. });
  27543. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27544. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27545. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27546. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27547. _this._labelsEnabled = element.checked;
  27548. if (!_this._labelsEnabled) {
  27549. _this._clearLabels();
  27550. }
  27551. });
  27552. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27553. if (element.checked) {
  27554. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27555. }
  27556. else {
  27557. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27558. }
  27559. });
  27560. ;
  27561. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27562. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27563. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27564. if (element.checked) {
  27565. _this._scene.forceWireframe = false;
  27566. _this._scene.forcePointsCloud = false;
  27567. }
  27568. });
  27569. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27570. if (element.checked) {
  27571. _this._scene.forceWireframe = true;
  27572. _this._scene.forcePointsCloud = false;
  27573. }
  27574. });
  27575. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27576. if (element.checked) {
  27577. _this._scene.forceWireframe = false;
  27578. _this._scene.forcePointsCloud = true;
  27579. }
  27580. });
  27581. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27582. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27583. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27584. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27585. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27586. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27587. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27588. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27589. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27590. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27591. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27592. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27593. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27594. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27595. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27596. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27597. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27598. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27599. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27600. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27601. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27602. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27603. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27604. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27605. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27606. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27607. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27608. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27609. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27610. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27611. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27612. if (element.checked) {
  27613. _this._scene.headphone = true;
  27614. }
  27615. });
  27616. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27617. if (element.checked) {
  27618. _this._scene.headphone = false;
  27619. }
  27620. });
  27621. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27622. _this._scene.audioEnabled = !element.checked;
  27623. });
  27624. }
  27625. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27626. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27627. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27628. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27629. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27630. if (_this._camera) {
  27631. console.log(_this._camera);
  27632. }
  27633. else {
  27634. console.warn("No camera defined, or debug layer created before camera creation!");
  27635. }
  27636. });
  27637. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27638. this._globalDiv.appendChild(this._statsDiv);
  27639. this._globalDiv.appendChild(this._logDiv);
  27640. this._globalDiv.appendChild(this._optionsDiv);
  27641. this._globalDiv.appendChild(this._treeDiv);
  27642. }
  27643. };
  27644. DebugLayer.prototype._displayStats = function () {
  27645. var scene = this._scene;
  27646. var engine = scene.getEngine();
  27647. var glInfo = engine.getGlInfo();
  27648. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27649. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27650. + "<b>Count</b><br>"
  27651. + "Total meshes: " + scene.meshes.length + "<br>"
  27652. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27653. + "Total materials: " + scene.materials.length + "<br>"
  27654. + "Total textures: " + scene.textures.length + "<br>"
  27655. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27656. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27657. + "Active bones: " + scene.getActiveBones() + "<br>"
  27658. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27659. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27660. + "<b>Duration</b><br>"
  27661. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27662. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27663. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27664. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27665. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27666. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27667. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27668. + "</div>"
  27669. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27670. + "<b>Extensions</b><br>"
  27671. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27672. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27673. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27674. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27675. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27676. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27677. + "<b>Caps.</b><br>"
  27678. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27679. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27680. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27681. + "</div><br>"
  27682. + "<b>Info</b><br>"
  27683. + glInfo.version + "<br>"
  27684. + glInfo.renderer + "<br>";
  27685. if (this.customStatsFunction) {
  27686. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27687. }
  27688. };
  27689. return DebugLayer;
  27690. })();
  27691. BABYLON.DebugLayer = DebugLayer;
  27692. })(BABYLON || (BABYLON = {}));
  27693. var BABYLON;
  27694. (function (BABYLON) {
  27695. var DefaultLoadingScreen = (function () {
  27696. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27697. var _this = this;
  27698. if (_loadingText === void 0) { _loadingText = ""; }
  27699. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27700. this._renderingCanvas = _renderingCanvas;
  27701. this._loadingText = _loadingText;
  27702. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27703. // Resize
  27704. this._resizeLoadingUI = function () {
  27705. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27706. _this._loadingDiv.style.position = "absolute";
  27707. _this._loadingDiv.style.left = canvasRect.left + "px";
  27708. _this._loadingDiv.style.top = canvasRect.top + "px";
  27709. _this._loadingDiv.style.width = canvasRect.width + "px";
  27710. _this._loadingDiv.style.height = canvasRect.height + "px";
  27711. };
  27712. }
  27713. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27714. var _this = this;
  27715. this._loadingDiv = document.createElement("div");
  27716. this._loadingDiv.id = "babylonjsLoadingDiv";
  27717. this._loadingDiv.style.opacity = "0";
  27718. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27719. // Loading text
  27720. this._loadingTextDiv = document.createElement("div");
  27721. this._loadingTextDiv.style.position = "absolute";
  27722. this._loadingTextDiv.style.left = "0";
  27723. this._loadingTextDiv.style.top = "50%";
  27724. this._loadingTextDiv.style.marginTop = "80px";
  27725. this._loadingTextDiv.style.width = "100%";
  27726. this._loadingTextDiv.style.height = "20px";
  27727. this._loadingTextDiv.style.fontFamily = "Arial";
  27728. this._loadingTextDiv.style.fontSize = "14px";
  27729. this._loadingTextDiv.style.color = "white";
  27730. this._loadingTextDiv.style.textAlign = "center";
  27731. this._loadingTextDiv.innerHTML = "Loading";
  27732. this._loadingDiv.appendChild(this._loadingTextDiv);
  27733. //set the predefined text
  27734. this._loadingTextDiv.innerHTML = this._loadingText;
  27735. // Loading img
  27736. var imgBack = new Image();
  27737. 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==";
  27738. imgBack.style.position = "absolute";
  27739. imgBack.style.left = "50%";
  27740. imgBack.style.top = "50%";
  27741. imgBack.style.marginLeft = "-50px";
  27742. imgBack.style.marginTop = "-50px";
  27743. imgBack.style.transition = "transform 1.0s ease";
  27744. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27745. var deg = 360;
  27746. var onTransitionEnd = function () {
  27747. deg += 360;
  27748. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27749. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27750. };
  27751. imgBack.addEventListener("transitionend", onTransitionEnd);
  27752. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27753. this._loadingDiv.appendChild(imgBack);
  27754. // front image
  27755. var imgFront = new Image();
  27756. 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=";
  27757. imgFront.style.position = "absolute";
  27758. imgFront.style.left = "50%";
  27759. imgFront.style.top = "50%";
  27760. imgFront.style.marginLeft = "-50px";
  27761. imgFront.style.marginTop = "-50px";
  27762. this._loadingDiv.appendChild(imgFront);
  27763. this._resizeLoadingUI();
  27764. window.addEventListener("resize", this._resizeLoadingUI);
  27765. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27766. document.body.appendChild(this._loadingDiv);
  27767. setTimeout(function () {
  27768. _this._loadingDiv.style.opacity = "1";
  27769. imgBack.style.transform = "rotateZ(360deg)";
  27770. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27771. }, 0);
  27772. };
  27773. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27774. var _this = this;
  27775. if (!this._loadingDiv) {
  27776. return;
  27777. }
  27778. var onTransitionEnd = function () {
  27779. if (!_this._loadingDiv) {
  27780. return;
  27781. }
  27782. document.body.removeChild(_this._loadingDiv);
  27783. window.removeEventListener("resize", _this._resizeLoadingUI);
  27784. _this._loadingDiv = null;
  27785. };
  27786. this._loadingDiv.style.opacity = "0";
  27787. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27788. };
  27789. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27790. set: function (text) {
  27791. this._loadingText = text;
  27792. if (this._loadingTextDiv) {
  27793. this._loadingTextDiv.innerHTML = this._loadingText;
  27794. }
  27795. },
  27796. enumerable: true,
  27797. configurable: true
  27798. });
  27799. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27800. get: function () {
  27801. return this._loadingDivBackgroundColor;
  27802. },
  27803. set: function (color) {
  27804. this._loadingDivBackgroundColor = color;
  27805. if (!this._loadingDiv) {
  27806. return;
  27807. }
  27808. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27809. },
  27810. enumerable: true,
  27811. configurable: true
  27812. });
  27813. return DefaultLoadingScreen;
  27814. })();
  27815. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27816. })(BABYLON || (BABYLON = {}));
  27817. var BABYLON;
  27818. (function (BABYLON) {
  27819. var SIMDVector3 = (function () {
  27820. function SIMDVector3() {
  27821. }
  27822. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27823. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27824. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27825. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27826. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27827. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27828. 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));
  27829. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27830. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27831. };
  27832. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27833. var v0 = SIMD.float32x4.splat(x);
  27834. var v1 = SIMD.float32x4.splat(y);
  27835. var v2 = SIMD.float32x4.splat(z);
  27836. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27837. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27838. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27839. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27840. 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));
  27841. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27842. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27843. };
  27844. return SIMDVector3;
  27845. })();
  27846. BABYLON.SIMDVector3 = SIMDVector3;
  27847. var SIMDMatrix = (function () {
  27848. function SIMDMatrix() {
  27849. }
  27850. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27851. if (offset === void 0) { offset = 0; }
  27852. var tm = this.m;
  27853. var om = other.m;
  27854. var om0 = SIMD.float32x4.load(om, 0);
  27855. var om1 = SIMD.float32x4.load(om, 4);
  27856. var om2 = SIMD.float32x4.load(om, 8);
  27857. var om3 = SIMD.float32x4.load(om, 12);
  27858. var tm0 = SIMD.float32x4.load(tm, 0);
  27859. 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)))));
  27860. var tm1 = SIMD.float32x4.load(tm, 4);
  27861. 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)))));
  27862. var tm2 = SIMD.float32x4.load(tm, 8);
  27863. 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)))));
  27864. var tm3 = SIMD.float32x4.load(tm, 12);
  27865. 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)))));
  27866. };
  27867. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27868. var src = this.m;
  27869. var dest = other.m;
  27870. var row0, row1, row2, row3;
  27871. var tmp1;
  27872. var minor0, minor1, minor2, minor3;
  27873. var det;
  27874. // Load the 4 rows
  27875. var src0 = SIMD.float32x4.load(src, 0);
  27876. var src1 = SIMD.float32x4.load(src, 4);
  27877. var src2 = SIMD.float32x4.load(src, 8);
  27878. var src3 = SIMD.float32x4.load(src, 12);
  27879. // Transpose the source matrix. Sort of. Not a true transpose operation
  27880. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27881. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27882. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27883. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27884. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27885. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27886. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27887. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27888. // This is a true transposition, but it will lead to an incorrect result
  27889. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27890. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27891. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27892. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27893. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27894. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27895. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27896. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27897. // ----
  27898. tmp1 = SIMD.float32x4.mul(row2, row3);
  27899. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27900. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27901. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27902. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27903. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27904. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27905. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27906. // ----
  27907. tmp1 = SIMD.float32x4.mul(row1, row2);
  27908. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27909. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27910. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27911. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27912. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27913. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27914. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27915. // ----
  27916. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27917. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27918. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27919. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27920. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27921. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27922. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27923. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27924. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27925. // ----
  27926. tmp1 = SIMD.float32x4.mul(row0, row1);
  27927. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27928. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27929. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27930. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27931. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27932. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27933. // ----
  27934. tmp1 = SIMD.float32x4.mul(row0, row3);
  27935. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27936. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27937. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27938. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27939. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27940. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27941. // ----
  27942. tmp1 = SIMD.float32x4.mul(row0, row2);
  27943. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27944. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27945. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27946. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27947. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27948. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27949. // Compute determinant
  27950. det = SIMD.float32x4.mul(row0, minor0);
  27951. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27952. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27953. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27954. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27955. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27956. // These shuffles aren't necessary if the faulty transposition is done
  27957. // up at the top of this function.
  27958. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27959. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27960. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27961. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27962. // Compute final values by multiplying with 1/det
  27963. minor0 = SIMD.float32x4.mul(det, minor0);
  27964. minor1 = SIMD.float32x4.mul(det, minor1);
  27965. minor2 = SIMD.float32x4.mul(det, minor2);
  27966. minor3 = SIMD.float32x4.mul(det, minor3);
  27967. SIMD.float32x4.store(dest, 0, minor0);
  27968. SIMD.float32x4.store(dest, 4, minor1);
  27969. SIMD.float32x4.store(dest, 8, minor2);
  27970. SIMD.float32x4.store(dest, 12, minor3);
  27971. return this;
  27972. };
  27973. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27974. var out = result.m;
  27975. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27976. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27977. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27978. // cc.kmVec3Subtract(f, pCenter, pEye);
  27979. var f = SIMD.float32x4.sub(center, eye);
  27980. // cc.kmVec3Normalize(f, f);
  27981. var tmp = SIMD.float32x4.mul(f, f);
  27982. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27983. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27984. // cc.kmVec3Assign(up, pUp);
  27985. // cc.kmVec3Normalize(up, up);
  27986. tmp = SIMD.float32x4.mul(up, up);
  27987. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27988. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27989. // cc.kmVec3Cross(s, f, up);
  27990. 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)));
  27991. // cc.kmVec3Normalize(s, s);
  27992. tmp = SIMD.float32x4.mul(s, s);
  27993. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27994. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27995. // cc.kmVec3Cross(u, s, f);
  27996. 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)));
  27997. // cc.kmVec3Normalize(s, s);
  27998. tmp = SIMD.float32x4.mul(s, s);
  27999. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28000. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28001. var zero = SIMD.float32x4.splat(0.0);
  28002. s = SIMD.float32x4.neg(s);
  28003. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28004. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28005. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28006. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28007. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28008. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28009. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28010. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28011. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28012. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28013. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28014. var b3 = SIMD.float32x4.neg(eye);
  28015. b3 = SIMD.float32x4.withW(b3, 1.0);
  28016. 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)))));
  28017. 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)))));
  28018. 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)))));
  28019. 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)))));
  28020. };
  28021. return SIMDMatrix;
  28022. })();
  28023. BABYLON.SIMDMatrix = SIMDMatrix;
  28024. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28025. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28026. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28027. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28028. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28029. var SIMDHelper = (function () {
  28030. function SIMDHelper() {
  28031. }
  28032. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28033. get: function () {
  28034. return SIMDHelper._isEnabled;
  28035. },
  28036. enumerable: true,
  28037. configurable: true
  28038. });
  28039. SIMDHelper.DisableSIMD = function () {
  28040. // Replace functions
  28041. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28042. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28043. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28044. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28046. SIMDHelper._isEnabled = false;
  28047. };
  28048. SIMDHelper.EnableSIMD = function () {
  28049. if (window.SIMD === undefined) {
  28050. return;
  28051. }
  28052. // Replace functions
  28053. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28054. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28055. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28056. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28057. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28058. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28059. get: function () { return this._data[0]; },
  28060. set: function (value) {
  28061. if (!this._data) {
  28062. this._data = new Float32Array(3);
  28063. }
  28064. this._data[0] = value;
  28065. }
  28066. });
  28067. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28068. get: function () { return this._data[1]; },
  28069. set: function (value) {
  28070. this._data[1] = value;
  28071. }
  28072. });
  28073. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28074. get: function () { return this._data[2]; },
  28075. set: function (value) {
  28076. this._data[2] = value;
  28077. }
  28078. });
  28079. SIMDHelper._isEnabled = true;
  28080. };
  28081. SIMDHelper._isEnabled = false;
  28082. return SIMDHelper;
  28083. })();
  28084. BABYLON.SIMDHelper = SIMDHelper;
  28085. })(BABYLON || (BABYLON = {}));
  28086. var BABYLON;
  28087. (function (BABYLON) {
  28088. var ShaderMaterial = (function (_super) {
  28089. __extends(ShaderMaterial, _super);
  28090. function ShaderMaterial(name, scene, shaderPath, options) {
  28091. _super.call(this, name, scene);
  28092. this._textures = {};
  28093. this._floats = {};
  28094. this._floatsArrays = {};
  28095. this._colors3 = {};
  28096. this._colors4 = {};
  28097. this._vectors2 = {};
  28098. this._vectors3 = {};
  28099. this._vectors4 = {};
  28100. this._matrices = {};
  28101. this._matrices3x3 = {};
  28102. this._matrices2x2 = {};
  28103. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28104. this._shaderPath = shaderPath;
  28105. options.needAlphaBlending = options.needAlphaBlending || false;
  28106. options.needAlphaTesting = options.needAlphaTesting || false;
  28107. options.attributes = options.attributes || ["position", "normal", "uv"];
  28108. options.uniforms = options.uniforms || ["worldViewProjection"];
  28109. options.samplers = options.samplers || [];
  28110. options.defines = options.defines || [];
  28111. this._options = options;
  28112. }
  28113. ShaderMaterial.prototype.needAlphaBlending = function () {
  28114. return this._options.needAlphaBlending;
  28115. };
  28116. ShaderMaterial.prototype.needAlphaTesting = function () {
  28117. return this._options.needAlphaTesting;
  28118. };
  28119. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28120. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28121. this._options.uniforms.push(uniformName);
  28122. }
  28123. };
  28124. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28125. if (this._options.samplers.indexOf(name) === -1) {
  28126. this._options.samplers.push(name);
  28127. }
  28128. this._textures[name] = texture;
  28129. return this;
  28130. };
  28131. ShaderMaterial.prototype.setFloat = function (name, value) {
  28132. this._checkUniform(name);
  28133. this._floats[name] = value;
  28134. return this;
  28135. };
  28136. ShaderMaterial.prototype.setFloats = function (name, value) {
  28137. this._checkUniform(name);
  28138. this._floatsArrays[name] = value;
  28139. return this;
  28140. };
  28141. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28142. this._checkUniform(name);
  28143. this._colors3[name] = value;
  28144. return this;
  28145. };
  28146. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28147. this._checkUniform(name);
  28148. this._colors4[name] = value;
  28149. return this;
  28150. };
  28151. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28152. this._checkUniform(name);
  28153. this._vectors2[name] = value;
  28154. return this;
  28155. };
  28156. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28157. this._checkUniform(name);
  28158. this._vectors3[name] = value;
  28159. return this;
  28160. };
  28161. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28162. this._checkUniform(name);
  28163. this._vectors4[name] = value;
  28164. return this;
  28165. };
  28166. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28167. this._checkUniform(name);
  28168. this._matrices[name] = value;
  28169. return this;
  28170. };
  28171. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28172. this._checkUniform(name);
  28173. this._matrices3x3[name] = value;
  28174. return this;
  28175. };
  28176. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28177. this._checkUniform(name);
  28178. this._matrices2x2[name] = value;
  28179. return this;
  28180. };
  28181. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28182. var scene = this.getScene();
  28183. var engine = scene.getEngine();
  28184. if (!this.checkReadyOnEveryCall) {
  28185. if (this._renderId === scene.getRenderId()) {
  28186. return true;
  28187. }
  28188. }
  28189. // Instances
  28190. var defines = [];
  28191. var fallbacks = new BABYLON.EffectFallbacks();
  28192. if (useInstances) {
  28193. defines.push("#define INSTANCES");
  28194. }
  28195. for (var index = 0; index < this._options.defines.length; index++) {
  28196. defines.push(this._options.defines[index]);
  28197. }
  28198. // Bones
  28199. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28200. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28201. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28202. fallbacks.addCPUSkinningFallback(0, mesh);
  28203. }
  28204. // Alpha test
  28205. if (engine.getAlphaTesting()) {
  28206. defines.push("#define ALPHATEST");
  28207. }
  28208. var previousEffect = this._effect;
  28209. var join = defines.join("\n");
  28210. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28211. if (!this._effect.isReady()) {
  28212. return false;
  28213. }
  28214. if (previousEffect !== this._effect) {
  28215. scene.resetCachedMaterial();
  28216. }
  28217. this._renderId = scene.getRenderId();
  28218. return true;
  28219. };
  28220. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28221. var scene = this.getScene();
  28222. if (this._options.uniforms.indexOf("world") !== -1) {
  28223. this._effect.setMatrix("world", world);
  28224. }
  28225. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28226. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28227. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28228. }
  28229. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28230. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28231. }
  28232. };
  28233. ShaderMaterial.prototype.bind = function (world, mesh) {
  28234. // Std values
  28235. this.bindOnlyWorldMatrix(world);
  28236. if (this.getScene().getCachedMaterial() !== this) {
  28237. if (this._options.uniforms.indexOf("view") !== -1) {
  28238. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28239. }
  28240. if (this._options.uniforms.indexOf("projection") !== -1) {
  28241. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28242. }
  28243. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28244. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28245. }
  28246. // Bones
  28247. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28248. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28249. }
  28250. // Texture
  28251. for (var name in this._textures) {
  28252. this._effect.setTexture(name, this._textures[name]);
  28253. }
  28254. // Float
  28255. for (name in this._floats) {
  28256. this._effect.setFloat(name, this._floats[name]);
  28257. }
  28258. // Float s
  28259. for (name in this._floatsArrays) {
  28260. this._effect.setArray(name, this._floatsArrays[name]);
  28261. }
  28262. // Color3
  28263. for (name in this._colors3) {
  28264. this._effect.setColor3(name, this._colors3[name]);
  28265. }
  28266. // Color4
  28267. for (name in this._colors4) {
  28268. var color = this._colors4[name];
  28269. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28270. }
  28271. // Vector2
  28272. for (name in this._vectors2) {
  28273. this._effect.setVector2(name, this._vectors2[name]);
  28274. }
  28275. // Vector3
  28276. for (name in this._vectors3) {
  28277. this._effect.setVector3(name, this._vectors3[name]);
  28278. }
  28279. // Vector4
  28280. for (name in this._vectors4) {
  28281. this._effect.setVector4(name, this._vectors4[name]);
  28282. }
  28283. // Matrix
  28284. for (name in this._matrices) {
  28285. this._effect.setMatrix(name, this._matrices[name]);
  28286. }
  28287. // Matrix 3x3
  28288. for (name in this._matrices3x3) {
  28289. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28290. }
  28291. // Matrix 2x2
  28292. for (name in this._matrices2x2) {
  28293. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28294. }
  28295. }
  28296. _super.prototype.bind.call(this, world, mesh);
  28297. };
  28298. ShaderMaterial.prototype.clone = function (name) {
  28299. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28300. return newShaderMaterial;
  28301. };
  28302. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28303. for (var name in this._textures) {
  28304. this._textures[name].dispose();
  28305. }
  28306. this._textures = {};
  28307. _super.prototype.dispose.call(this, forceDisposeEffect);
  28308. };
  28309. ShaderMaterial.prototype.serialize = function () {
  28310. var serializationObject = _super.prototype.serialize.call(this);
  28311. serializationObject.options = this._options;
  28312. serializationObject.shaderPath = this._shaderPath;
  28313. serializationObject.customType = "BABYLON.ShaderMaterial";
  28314. // Texture
  28315. serializationObject.textures = {};
  28316. for (var name in this._textures) {
  28317. serializationObject.textures[name] = this._textures[name].serialize();
  28318. }
  28319. // Float
  28320. serializationObject.floats = {};
  28321. for (name in this._floats) {
  28322. serializationObject.floats[name] = this._floats[name];
  28323. }
  28324. // Float s
  28325. serializationObject.floatArrays = {};
  28326. for (name in this._floatsArrays) {
  28327. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28328. }
  28329. // Color3
  28330. serializationObject.colors3 = {};
  28331. for (name in this._colors3) {
  28332. serializationObject.colors3[name] = this._colors3[name].asArray();
  28333. }
  28334. // Color4
  28335. serializationObject.colors4 = {};
  28336. for (name in this._colors4) {
  28337. serializationObject.colors4[name] = this._colors4[name].asArray();
  28338. }
  28339. // Vector2
  28340. serializationObject.vectors2 = {};
  28341. for (name in this._vectors2) {
  28342. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28343. }
  28344. // Vector3
  28345. serializationObject.vectors3 = {};
  28346. for (name in this._vectors3) {
  28347. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28348. }
  28349. // Vector4
  28350. serializationObject.vectors4 = {};
  28351. for (name in this._vectors4) {
  28352. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28353. }
  28354. // Matrix
  28355. serializationObject.matrices = {};
  28356. for (name in this._matrices) {
  28357. serializationObject.matrices[name] = this._matrices[name].asArray();
  28358. }
  28359. // Matrix 3x3
  28360. serializationObject.matrices3x3 = {};
  28361. for (name in this._matrices3x3) {
  28362. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28363. }
  28364. // Matrix 2x2
  28365. serializationObject.matrices2x2 = {};
  28366. for (name in this._matrices2x2) {
  28367. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28368. }
  28369. return serializationObject;
  28370. };
  28371. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28372. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28373. // Texture
  28374. for (var name in source.textures) {
  28375. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28376. }
  28377. // Float
  28378. for (name in source.floats) {
  28379. material.setFloat(name, source.floats[name]);
  28380. }
  28381. // Float s
  28382. for (name in source.floatsArrays) {
  28383. material.setFloats(name, source.floatsArrays[name]);
  28384. }
  28385. // Color3
  28386. for (name in source.colors3) {
  28387. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28388. }
  28389. // Color4
  28390. for (name in source.colors4) {
  28391. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28392. }
  28393. // Vector2
  28394. for (name in source.vectors2) {
  28395. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28396. }
  28397. // Vector3
  28398. for (name in source.vectors3) {
  28399. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28400. }
  28401. // Vector4
  28402. for (name in source.vectors4) {
  28403. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28404. }
  28405. // Matrix
  28406. for (name in source.matrices) {
  28407. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28408. }
  28409. // Matrix 3x3
  28410. for (name in source.matrices3x3) {
  28411. material.setMatrix3x3(name, source.matrices3x3[name]);
  28412. }
  28413. // Matrix 2x2
  28414. for (name in source.matrices2x2) {
  28415. material.setMatrix2x2(name, source.matrices2x2[name]);
  28416. }
  28417. return material;
  28418. };
  28419. return ShaderMaterial;
  28420. })(BABYLON.Material);
  28421. BABYLON.ShaderMaterial = ShaderMaterial;
  28422. })(BABYLON || (BABYLON = {}));
  28423. var BABYLON;
  28424. (function (BABYLON) {
  28425. var Internals;
  28426. (function (Internals) {
  28427. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28428. // All values and structures referenced from:
  28429. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28430. var DDS_MAGIC = 0x20534444;
  28431. 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;
  28432. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28433. 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;
  28434. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28435. function FourCCToInt32(value) {
  28436. return value.charCodeAt(0) +
  28437. (value.charCodeAt(1) << 8) +
  28438. (value.charCodeAt(2) << 16) +
  28439. (value.charCodeAt(3) << 24);
  28440. }
  28441. function Int32ToFourCC(value) {
  28442. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28443. }
  28444. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28445. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28446. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28447. var headerLengthInt = 31; // The header length in 32 bit ints
  28448. // Offsets into the header array
  28449. var off_magic = 0;
  28450. var off_size = 1;
  28451. var off_flags = 2;
  28452. var off_height = 3;
  28453. var off_width = 4;
  28454. var off_mipmapCount = 7;
  28455. var off_pfFlags = 20;
  28456. var off_pfFourCC = 21;
  28457. var off_RGBbpp = 22;
  28458. var off_RMask = 23;
  28459. var off_GMask = 24;
  28460. var off_BMask = 25;
  28461. var off_AMask = 26;
  28462. var off_caps1 = 27;
  28463. var off_caps2 = 28;
  28464. ;
  28465. var DDSTools = (function () {
  28466. function DDSTools() {
  28467. }
  28468. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28469. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28470. var mipmapCount = 1;
  28471. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28472. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28473. }
  28474. return {
  28475. width: header[off_width],
  28476. height: header[off_height],
  28477. mipmapCount: mipmapCount,
  28478. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28479. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28480. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28481. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28482. };
  28483. };
  28484. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28485. var byteArray = new Uint8Array(dataLength);
  28486. var srcData = new Uint8Array(arrayBuffer);
  28487. var index = 0;
  28488. for (var y = height - 1; y >= 0; y--) {
  28489. for (var x = 0; x < width; x++) {
  28490. var srcPos = dataOffset + (x + y * width) * 4;
  28491. byteArray[index + 2] = srcData[srcPos];
  28492. byteArray[index + 1] = srcData[srcPos + 1];
  28493. byteArray[index] = srcData[srcPos + 2];
  28494. byteArray[index + 3] = srcData[srcPos + 3];
  28495. index += 4;
  28496. }
  28497. }
  28498. return byteArray;
  28499. };
  28500. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28501. var byteArray = new Uint8Array(dataLength);
  28502. var srcData = new Uint8Array(arrayBuffer);
  28503. var index = 0;
  28504. for (var y = height - 1; y >= 0; y--) {
  28505. for (var x = 0; x < width; x++) {
  28506. var srcPos = dataOffset + (x + y * width) * 3;
  28507. byteArray[index + 2] = srcData[srcPos];
  28508. byteArray[index + 1] = srcData[srcPos + 1];
  28509. byteArray[index] = srcData[srcPos + 2];
  28510. index += 3;
  28511. }
  28512. }
  28513. return byteArray;
  28514. };
  28515. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28516. var byteArray = new Uint8Array(dataLength);
  28517. var srcData = new Uint8Array(arrayBuffer);
  28518. var index = 0;
  28519. for (var y = height - 1; y >= 0; y--) {
  28520. for (var x = 0; x < width; x++) {
  28521. var srcPos = dataOffset + (x + y * width);
  28522. byteArray[index] = srcData[srcPos];
  28523. index++;
  28524. }
  28525. }
  28526. return byteArray;
  28527. };
  28528. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28529. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28530. if (header[off_magic] != DDS_MAGIC) {
  28531. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28532. return;
  28533. }
  28534. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28535. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28536. return;
  28537. }
  28538. if (info.isFourCC) {
  28539. fourCC = header[off_pfFourCC];
  28540. switch (fourCC) {
  28541. case FOURCC_DXT1:
  28542. blockBytes = 8;
  28543. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28544. break;
  28545. case FOURCC_DXT3:
  28546. blockBytes = 16;
  28547. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28548. break;
  28549. case FOURCC_DXT5:
  28550. blockBytes = 16;
  28551. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28552. break;
  28553. default:
  28554. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28555. return;
  28556. }
  28557. }
  28558. mipmapCount = 1;
  28559. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28560. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28561. }
  28562. var bpp = header[off_RGBbpp];
  28563. for (var face = 0; face < faces; face++) {
  28564. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28565. width = header[off_width];
  28566. height = header[off_height];
  28567. dataOffset = header[off_size] + 4;
  28568. for (i = 0; i < mipmapCount; ++i) {
  28569. if (info.isRGB) {
  28570. if (bpp === 24) {
  28571. dataLength = width * height * 3;
  28572. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28573. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28574. }
  28575. else {
  28576. dataLength = width * height * 4;
  28577. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28578. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28579. }
  28580. }
  28581. else if (info.isLuminance) {
  28582. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28583. var unpaddedRowSize = width;
  28584. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28585. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28586. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28587. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28588. }
  28589. else {
  28590. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28591. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28592. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28593. }
  28594. dataOffset += dataLength;
  28595. width *= 0.5;
  28596. height *= 0.5;
  28597. width = Math.max(1.0, width);
  28598. height = Math.max(1.0, height);
  28599. }
  28600. }
  28601. };
  28602. return DDSTools;
  28603. })();
  28604. Internals.DDSTools = DDSTools;
  28605. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28606. })(BABYLON || (BABYLON = {}));
  28607. var BABYLON;
  28608. (function (BABYLON) {
  28609. var CannonJSPlugin = (function () {
  28610. function CannonJSPlugin() {
  28611. this._registeredMeshes = [];
  28612. this._physicsMaterials = [];
  28613. this.name = "cannon";
  28614. this.updateBodyPosition = function (mesh) {
  28615. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28616. var registeredMesh = this._registeredMeshes[index];
  28617. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28618. var body = registeredMesh.body;
  28619. var center = mesh.getBoundingInfo().boundingBox.center;
  28620. body.position.set(center.x, center.y, center.z);
  28621. body.quaternion.copy(mesh.rotationQuaternion);
  28622. if (registeredMesh.deltaRotation) {
  28623. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28624. body.quaternion = body.quaternion.mult(tmpQ);
  28625. }
  28626. if (registeredMesh.heightmap) {
  28627. //calculate the correct body position:
  28628. var rotationQuaternion = mesh.rotationQuaternion;
  28629. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28630. mesh.computeWorldMatrix(true);
  28631. //get original center with no rotation
  28632. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28633. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28634. //rotation is back
  28635. mesh.rotationQuaternion = rotationQuaternion;
  28636. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28637. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28638. mesh.setPivotMatrix(p);
  28639. mesh.computeWorldMatrix(true);
  28640. //calculate the translation
  28641. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28642. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28643. //add it inverted to the delta
  28644. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28645. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28646. mesh.setPivotMatrix(oldPivot);
  28647. mesh.computeWorldMatrix(true);
  28648. }
  28649. return;
  28650. }
  28651. }
  28652. };
  28653. }
  28654. CannonJSPlugin.prototype.initialize = function (iterations) {
  28655. if (iterations === void 0) { iterations = 10; }
  28656. this._world = new CANNON.World();
  28657. this._world.broadphase = new CANNON.NaiveBroadphase();
  28658. this._world.solver.iterations = iterations;
  28659. };
  28660. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28661. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28662. };
  28663. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28664. var _this = this;
  28665. this._world.step(delta);
  28666. this._registeredMeshes.forEach(function (registeredMesh) {
  28667. // Body position
  28668. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28669. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28670. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28671. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28672. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28673. if (registeredMesh.deltaRotation) {
  28674. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28675. }
  28676. //is the physics collision callback is set?
  28677. if (registeredMesh.mesh.onPhysicsCollide) {
  28678. if (!registeredMesh.collisionFunction) {
  28679. registeredMesh.collisionFunction = function (e) {
  28680. //find the mesh that collided with the registered mesh
  28681. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28682. if (_this._registeredMeshes[idx].body == e.body) {
  28683. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28684. }
  28685. }
  28686. };
  28687. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28688. }
  28689. }
  28690. else {
  28691. //unregister, in case the function was removed for some reason
  28692. if (registeredMesh.collisionFunction) {
  28693. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28694. }
  28695. }
  28696. });
  28697. };
  28698. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28699. this._gravity = gravity;
  28700. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28701. };
  28702. CannonJSPlugin.prototype.getGravity = function () {
  28703. return this._gravity;
  28704. };
  28705. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28706. this.unregisterMesh(mesh);
  28707. if (!mesh.rotationQuaternion) {
  28708. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28709. }
  28710. mesh.computeWorldMatrix(true);
  28711. var shape = this._createShape(mesh, impostor);
  28712. return this._createRigidBodyFromShape(shape, mesh, options);
  28713. };
  28714. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28715. //get the correct bounding box
  28716. var oldQuaternion = mesh.rotationQuaternion;
  28717. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28718. mesh.computeWorldMatrix(true);
  28719. var returnValue;
  28720. switch (impostor) {
  28721. case BABYLON.PhysicsEngine.SphereImpostor:
  28722. var bbox = mesh.getBoundingInfo().boundingBox;
  28723. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28724. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28725. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28726. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28727. break;
  28728. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28729. case BABYLON.PhysicsEngine.CylinderImpostor:
  28730. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28731. case BABYLON.PhysicsEngine.BoxImpostor:
  28732. bbox = mesh.getBoundingInfo().boundingBox;
  28733. var min = bbox.minimumWorld;
  28734. var max = bbox.maximumWorld;
  28735. var box = max.subtract(min).scale(0.5);
  28736. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28737. break;
  28738. case BABYLON.PhysicsEngine.PlaneImpostor:
  28739. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28740. returnValue = new CANNON.Plane();
  28741. break;
  28742. case BABYLON.PhysicsEngine.MeshImpostor:
  28743. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28744. var rawFaces = mesh.getIndices();
  28745. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28746. break;
  28747. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28748. returnValue = this._createHeightmap(mesh);
  28749. break;
  28750. }
  28751. mesh.rotationQuaternion = oldQuaternion;
  28752. return returnValue;
  28753. };
  28754. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28755. var verts = [], faces = [];
  28756. mesh.computeWorldMatrix(true);
  28757. //reuse this variable
  28758. var transformed = BABYLON.Vector3.Zero();
  28759. // Get vertices
  28760. for (var i = 0; i < rawVerts.length; i += 3) {
  28761. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28762. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28763. }
  28764. // Get faces
  28765. for (var j = 0; j < rawFaces.length; j += 3) {
  28766. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28767. }
  28768. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28769. return shape;
  28770. };
  28771. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28772. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28773. var matrix = [];
  28774. //For now pointDepth will not be used and will be automatically calculated.
  28775. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28776. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28777. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28778. var elementSize = dim * 2 / arraySize;
  28779. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28780. for (var i = 0; i < pos.length; i = i + 3) {
  28781. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28782. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28783. var y = pos[i + 1] + minY;
  28784. if (!matrix[x]) {
  28785. matrix[x] = [];
  28786. }
  28787. if (!matrix[x][z]) {
  28788. matrix[x][z] = y;
  28789. }
  28790. matrix[x][z] = Math.max(y, matrix[x][z]);
  28791. }
  28792. for (var x = 0; x <= arraySize; ++x) {
  28793. if (!matrix[x]) {
  28794. var loc = 1;
  28795. while (!matrix[(x + loc) % arraySize]) {
  28796. loc++;
  28797. }
  28798. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28799. }
  28800. for (var z = 0; z <= arraySize; ++z) {
  28801. if (!matrix[x][z]) {
  28802. var loc = 1;
  28803. var newValue;
  28804. while (newValue === undefined) {
  28805. newValue = matrix[x][(z + loc++) % arraySize];
  28806. }
  28807. matrix[x][z] = newValue;
  28808. }
  28809. }
  28810. }
  28811. var shape = new CANNON.Heightfield(matrix, {
  28812. elementSize: elementSize
  28813. });
  28814. //For future reference, needed for body transformation
  28815. shape.minY = minY;
  28816. return shape;
  28817. };
  28818. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28819. var index;
  28820. var mat;
  28821. for (index = 0; index < this._physicsMaterials.length; index++) {
  28822. mat = this._physicsMaterials[index];
  28823. if (mat.friction === friction && mat.restitution === restitution) {
  28824. return mat;
  28825. }
  28826. }
  28827. var currentMat = new CANNON.Material("mat");
  28828. this._physicsMaterials.push(currentMat);
  28829. for (index = 0; index < this._physicsMaterials.length; index++) {
  28830. mat = this._physicsMaterials[index];
  28831. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28832. this._world.addContactMaterial(contactMaterial);
  28833. }
  28834. return currentMat;
  28835. };
  28836. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28837. if (!mesh.rotationQuaternion) {
  28838. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28839. }
  28840. // The delta between the mesh position and the mesh bounding box center
  28841. var bbox = mesh.getBoundingInfo().boundingBox;
  28842. var deltaPosition = mesh.position.subtract(bbox.center);
  28843. var deltaRotation;
  28844. var material = this._addMaterial(options.friction, options.restitution);
  28845. var body = new CANNON.Body({
  28846. mass: options.mass,
  28847. material: material,
  28848. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28849. });
  28850. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28851. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28852. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28853. //-90 DEG in X, precalculated
  28854. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28855. body.quaternion = body.quaternion.mult(tmpQ);
  28856. //Invert! (Precalculated, 90 deg in X)
  28857. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28858. }
  28859. //If it is a heightfield, if should be centered.
  28860. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28861. //calculate the correct body position:
  28862. var rotationQuaternion = mesh.rotationQuaternion;
  28863. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28864. mesh.computeWorldMatrix(true);
  28865. //get original center with no rotation
  28866. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28867. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28868. //rotation is back
  28869. mesh.rotationQuaternion = rotationQuaternion;
  28870. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28871. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28872. mesh.setPivotMatrix(p);
  28873. mesh.computeWorldMatrix(true);
  28874. //calculate the translation
  28875. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28876. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28877. //add it inverted to the delta
  28878. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28879. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28880. mesh.setPivotMatrix(oldPivot);
  28881. mesh.computeWorldMatrix(true);
  28882. }
  28883. //add the shape
  28884. body.addShape(shape);
  28885. this._world.add(body);
  28886. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28887. return body;
  28888. };
  28889. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28890. var initialMesh = parts[0].mesh;
  28891. this.unregisterMesh(initialMesh);
  28892. initialMesh.computeWorldMatrix(true);
  28893. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28894. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28895. for (var index = 1; index < parts.length; index++) {
  28896. var mesh = parts[index].mesh;
  28897. mesh.computeWorldMatrix(true);
  28898. var shape = this._createShape(mesh, parts[index].impostor);
  28899. var localPosition = mesh.position;
  28900. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28901. }
  28902. return body;
  28903. };
  28904. CannonJSPlugin.prototype._unbindBody = function (body) {
  28905. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28906. var registeredMesh = this._registeredMeshes[index];
  28907. if (registeredMesh.body === body) {
  28908. this._world.remove(registeredMesh.body);
  28909. registeredMesh.body = null;
  28910. registeredMesh.delta = null;
  28911. registeredMesh.deltaRotation = null;
  28912. }
  28913. }
  28914. };
  28915. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28916. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28917. var registeredMesh = this._registeredMeshes[index];
  28918. if (registeredMesh.mesh === mesh) {
  28919. // Remove body
  28920. if (registeredMesh.body) {
  28921. this._unbindBody(registeredMesh.body);
  28922. }
  28923. this._registeredMeshes.splice(index, 1);
  28924. return;
  28925. }
  28926. }
  28927. };
  28928. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28929. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28930. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28931. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28932. var registeredMesh = this._registeredMeshes[index];
  28933. if (registeredMesh.mesh === mesh) {
  28934. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28935. return;
  28936. }
  28937. }
  28938. };
  28939. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28940. var body1 = null, body2 = null;
  28941. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28942. var registeredMesh = this._registeredMeshes[index];
  28943. if (registeredMesh.mesh === mesh1) {
  28944. body1 = registeredMesh.body;
  28945. }
  28946. else if (registeredMesh.mesh === mesh2) {
  28947. body2 = registeredMesh.body;
  28948. }
  28949. }
  28950. if (!body1 || !body2) {
  28951. return false;
  28952. }
  28953. 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));
  28954. this._world.addConstraint(constraint);
  28955. return true;
  28956. };
  28957. CannonJSPlugin.prototype.dispose = function () {
  28958. while (this._registeredMeshes.length) {
  28959. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28960. }
  28961. };
  28962. CannonJSPlugin.prototype.isSupported = function () {
  28963. return window.CANNON !== undefined;
  28964. };
  28965. CannonJSPlugin.prototype.getWorldObject = function () {
  28966. return this._world;
  28967. };
  28968. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28969. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28970. var registeredMesh = this._registeredMeshes[index];
  28971. if (registeredMesh.mesh === mesh) {
  28972. return registeredMesh.body;
  28973. }
  28974. }
  28975. return null;
  28976. };
  28977. return CannonJSPlugin;
  28978. })();
  28979. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28980. })(BABYLON || (BABYLON = {}));
  28981. var BABYLON;
  28982. (function (BABYLON) {
  28983. var OimoJSPlugin = (function () {
  28984. function OimoJSPlugin() {
  28985. this._registeredMeshes = [];
  28986. this.name = "oimo";
  28987. /**
  28988. * Update the body position according to the mesh position
  28989. * @param mesh
  28990. */
  28991. this.updateBodyPosition = function (mesh) {
  28992. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28993. var registeredMesh = this._registeredMeshes[index];
  28994. var body = registeredMesh.body.body;
  28995. var updated = false;
  28996. var newPosition;
  28997. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28998. mesh.computeWorldMatrix(true);
  28999. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29000. updated = true;
  29001. }
  29002. else if (registeredMesh.mesh.parent === mesh) {
  29003. mesh.computeWorldMatrix(true);
  29004. registeredMesh.mesh.computeWorldMatrix(true);
  29005. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29006. updated = true;
  29007. }
  29008. if (updated) {
  29009. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29010. body.setQuaternion(mesh.rotationQuaternion);
  29011. body.sleeping = false;
  29012. //force Oimo to update the body's position
  29013. body.updatePosition(1);
  29014. }
  29015. }
  29016. };
  29017. }
  29018. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29019. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29020. };
  29021. OimoJSPlugin.prototype.initialize = function (iterations) {
  29022. this._world = new OIMO.World(null, null, iterations);
  29023. this._world.clear();
  29024. };
  29025. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29026. this._gravity = this._world.gravity = gravity;
  29027. };
  29028. OimoJSPlugin.prototype.getGravity = function () {
  29029. return this._gravity;
  29030. };
  29031. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29032. this.unregisterMesh(mesh);
  29033. if (!mesh.rotationQuaternion) {
  29034. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29035. }
  29036. mesh.computeWorldMatrix(true);
  29037. var bbox = mesh.getBoundingInfo().boundingBox;
  29038. // The delta between the mesh position and the mesh bounding box center
  29039. var deltaPosition = mesh.position.subtract(bbox.center);
  29040. //calculate rotation to fit Oimo's needs (Euler...)
  29041. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29042. //get the correct bounding box
  29043. var oldQuaternion = mesh.rotationQuaternion;
  29044. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29045. mesh.computeWorldMatrix(true);
  29046. var bodyConfig = {
  29047. name: mesh.uniqueId,
  29048. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29049. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29050. move: options.mass != 0,
  29051. config: [options.mass, options.friction, options.restitution],
  29052. world: this._world
  29053. };
  29054. // register mesh
  29055. switch (impostor) {
  29056. case BABYLON.PhysicsEngine.SphereImpostor:
  29057. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29058. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29059. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29060. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29061. bodyConfig.type = 'sphere';
  29062. bodyConfig.size = [size];
  29063. break;
  29064. case BABYLON.PhysicsEngine.PlaneImpostor:
  29065. //Oimo "fakes" a cylinder as a box, so why don't we!
  29066. case BABYLON.PhysicsEngine.CylinderImpostor:
  29067. case BABYLON.PhysicsEngine.BoxImpostor:
  29068. var min = bbox.minimumWorld;
  29069. var max = bbox.maximumWorld;
  29070. var box = max.subtract(min);
  29071. var sizeX = this._checkWithEpsilon(box.x);
  29072. var sizeY = this._checkWithEpsilon(box.y);
  29073. var sizeZ = this._checkWithEpsilon(box.z);
  29074. bodyConfig.type = 'box';
  29075. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29076. break;
  29077. }
  29078. var body = new OIMO.Body(bodyConfig);
  29079. //We have to access the rigid body's properties to set the quaternion.
  29080. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29081. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29082. //TEST
  29083. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29084. //update the internal rotation matrix
  29085. //body.body.syncShapes();
  29086. this._registeredMeshes.push({
  29087. mesh: mesh,
  29088. body: body,
  29089. delta: deltaPosition
  29090. });
  29091. //for the sake of consistency.
  29092. mesh.rotationQuaternion = oldQuaternion;
  29093. return body;
  29094. };
  29095. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29096. var types = [], sizes = [], positions = [], rotations = [];
  29097. var initialMesh = parts[0].mesh;
  29098. for (var index = 0; index < parts.length; index++) {
  29099. var part = parts[index];
  29100. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29101. types.push(bodyParameters.type);
  29102. sizes.push.apply(sizes, bodyParameters.size);
  29103. positions.push.apply(positions, bodyParameters.pos);
  29104. rotations.push.apply(rotations, bodyParameters.rot);
  29105. }
  29106. var body = new OIMO.Body({
  29107. name: initialMesh.uniqueId,
  29108. type: types,
  29109. size: sizes,
  29110. pos: positions,
  29111. rot: rotations,
  29112. move: options.mass != 0,
  29113. config: [options.mass, options.friction, options.restitution],
  29114. world: this._world
  29115. });
  29116. //Reset the body's rotation to be of the initial mesh's.
  29117. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29118. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29119. this._registeredMeshes.push({
  29120. mesh: initialMesh,
  29121. body: body
  29122. });
  29123. return body;
  29124. };
  29125. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29126. var mesh = part.mesh;
  29127. if (!mesh.rotationQuaternion) {
  29128. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29129. }
  29130. // We need the bounding box/sphere info to compute the physics body
  29131. mesh.computeWorldMatrix(true);
  29132. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29133. var bodyParameters = {
  29134. name: mesh.uniqueId,
  29135. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29136. //A bug in Oimo (Body class) prevents us from using rot directly.
  29137. rot: [0, 0, 0],
  29138. //For future reference, if the bug will ever be fixed.
  29139. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29140. };
  29141. var oldQuaternion = mesh.rotationQuaternion;
  29142. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29143. mesh.computeWorldMatrix(true);
  29144. switch (part.impostor) {
  29145. case BABYLON.PhysicsEngine.SphereImpostor:
  29146. var bbox = mesh.getBoundingInfo().boundingBox;
  29147. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29148. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29149. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29150. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29151. bodyParameters.type = 'sphere';
  29152. bodyParameters.size = [size, size, size];
  29153. break;
  29154. case BABYLON.PhysicsEngine.PlaneImpostor:
  29155. case BABYLON.PhysicsEngine.CylinderImpostor:
  29156. case BABYLON.PhysicsEngine.BoxImpostor:
  29157. bbox = mesh.getBoundingInfo().boundingBox;
  29158. var min = bbox.minimumWorld;
  29159. var max = bbox.maximumWorld;
  29160. var box = max.subtract(min);
  29161. var sizeX = this._checkWithEpsilon(box.x);
  29162. var sizeY = this._checkWithEpsilon(box.y);
  29163. var sizeZ = this._checkWithEpsilon(box.z);
  29164. bodyParameters.type = 'box';
  29165. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29166. break;
  29167. }
  29168. mesh.rotationQuaternion = oldQuaternion;
  29169. return bodyParameters;
  29170. };
  29171. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29172. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29173. var registeredMesh = this._registeredMeshes[index];
  29174. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29175. if (registeredMesh.body) {
  29176. this._world.removeRigidBody(registeredMesh.body.body);
  29177. this._unbindBody(registeredMesh.body);
  29178. }
  29179. this._registeredMeshes.splice(index, 1);
  29180. return;
  29181. }
  29182. }
  29183. };
  29184. OimoJSPlugin.prototype._unbindBody = function (body) {
  29185. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29186. var registeredMesh = this._registeredMeshes[index];
  29187. if (registeredMesh.body === body) {
  29188. registeredMesh.body = null;
  29189. }
  29190. }
  29191. };
  29192. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29193. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29194. var registeredMesh = this._registeredMeshes[index];
  29195. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29196. // Get object mass to have a behaviour similar to cannon.js
  29197. var mass = registeredMesh.body.body.massInfo.mass;
  29198. // The force is scaled with the mass of object
  29199. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29200. return;
  29201. }
  29202. }
  29203. };
  29204. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29205. var body1 = null, body2 = null;
  29206. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29207. var registeredMesh = this._registeredMeshes[index];
  29208. if (registeredMesh.mesh === mesh1) {
  29209. body1 = registeredMesh.body.body;
  29210. }
  29211. else if (registeredMesh.mesh === mesh2) {
  29212. body2 = registeredMesh.body.body;
  29213. }
  29214. }
  29215. if (!body1 || !body2) {
  29216. return false;
  29217. }
  29218. if (!options) {
  29219. options = {};
  29220. }
  29221. new OIMO.Link({
  29222. type: options.type,
  29223. body1: body1,
  29224. body2: body2,
  29225. min: options.min,
  29226. max: options.max,
  29227. axe1: options.axe1,
  29228. axe2: options.axe2,
  29229. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29230. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29231. collision: options.collision,
  29232. spring: options.spring,
  29233. world: this._world
  29234. });
  29235. return true;
  29236. };
  29237. OimoJSPlugin.prototype.dispose = function () {
  29238. this._world.clear();
  29239. while (this._registeredMeshes.length) {
  29240. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29241. }
  29242. };
  29243. OimoJSPlugin.prototype.isSupported = function () {
  29244. return OIMO !== undefined;
  29245. };
  29246. OimoJSPlugin.prototype.getWorldObject = function () {
  29247. return this._world;
  29248. };
  29249. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29250. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29251. var registeredMesh = this._registeredMeshes[index];
  29252. if (registeredMesh.mesh === mesh) {
  29253. return registeredMesh.body;
  29254. }
  29255. }
  29256. return null;
  29257. };
  29258. OimoJSPlugin.prototype._getLastShape = function (body) {
  29259. var lastShape = body.shapes;
  29260. while (lastShape.next) {
  29261. lastShape = lastShape.next;
  29262. }
  29263. return lastShape;
  29264. };
  29265. OimoJSPlugin.prototype.runOneStep = function (time) {
  29266. this._world.step();
  29267. // Update the position of all registered meshes
  29268. var i = this._registeredMeshes.length;
  29269. var m;
  29270. while (i--) {
  29271. var body = this._registeredMeshes[i].body.body;
  29272. var mesh = this._registeredMeshes[i].mesh;
  29273. if (!this._registeredMeshes[i].delta) {
  29274. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29275. }
  29276. if (!body.sleeping) {
  29277. //TODO check that
  29278. if (body.shapes.next) {
  29279. var parentShape = this._getLastShape(body);
  29280. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29281. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29282. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29283. }
  29284. else {
  29285. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29286. }
  29287. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29288. mesh.computeWorldMatrix();
  29289. }
  29290. //check if the collide callback is set.
  29291. if (mesh.onPhysicsCollide) {
  29292. var meshUniqueName = mesh.uniqueId;
  29293. var contact = this._world.contacts;
  29294. while (contact !== null) {
  29295. //is this body colliding with any other?
  29296. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29297. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29298. //get the mesh and execute the callback
  29299. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29300. if (otherMesh)
  29301. mesh.onPhysicsCollide(otherMesh);
  29302. }
  29303. contact = contact.next;
  29304. }
  29305. }
  29306. }
  29307. };
  29308. return OimoJSPlugin;
  29309. })();
  29310. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29311. })(BABYLON || (BABYLON = {}));
  29312. var BABYLON;
  29313. (function (BABYLON) {
  29314. var DisplayPassPostProcess = (function (_super) {
  29315. __extends(DisplayPassPostProcess, _super);
  29316. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29317. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29318. }
  29319. return DisplayPassPostProcess;
  29320. })(BABYLON.PostProcess);
  29321. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29322. })(BABYLON || (BABYLON = {}));
  29323. var BABYLON;
  29324. (function (BABYLON) {
  29325. var SimplificationSettings = (function () {
  29326. function SimplificationSettings(quality, distance, optimizeMesh) {
  29327. this.quality = quality;
  29328. this.distance = distance;
  29329. this.optimizeMesh = optimizeMesh;
  29330. }
  29331. return SimplificationSettings;
  29332. })();
  29333. BABYLON.SimplificationSettings = SimplificationSettings;
  29334. var SimplificationQueue = (function () {
  29335. function SimplificationQueue() {
  29336. this.running = false;
  29337. this._simplificationArray = [];
  29338. }
  29339. SimplificationQueue.prototype.addTask = function (task) {
  29340. this._simplificationArray.push(task);
  29341. };
  29342. SimplificationQueue.prototype.executeNext = function () {
  29343. var task = this._simplificationArray.pop();
  29344. if (task) {
  29345. this.running = true;
  29346. this.runSimplification(task);
  29347. }
  29348. else {
  29349. this.running = false;
  29350. }
  29351. };
  29352. SimplificationQueue.prototype.runSimplification = function (task) {
  29353. var _this = this;
  29354. if (task.parallelProcessing) {
  29355. //parallel simplifier
  29356. task.settings.forEach(function (setting) {
  29357. var simplifier = _this.getSimplifier(task);
  29358. simplifier.simplify(setting, function (newMesh) {
  29359. task.mesh.addLODLevel(setting.distance, newMesh);
  29360. newMesh.isVisible = true;
  29361. //check if it is the last
  29362. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29363. //all done, run the success callback.
  29364. task.successCallback();
  29365. }
  29366. _this.executeNext();
  29367. });
  29368. });
  29369. }
  29370. else {
  29371. //single simplifier.
  29372. var simplifier = this.getSimplifier(task);
  29373. var runDecimation = function (setting, callback) {
  29374. simplifier.simplify(setting, function (newMesh) {
  29375. task.mesh.addLODLevel(setting.distance, newMesh);
  29376. newMesh.isVisible = true;
  29377. //run the next quality level
  29378. callback();
  29379. });
  29380. };
  29381. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29382. runDecimation(task.settings[loop.index], function () {
  29383. loop.executeNext();
  29384. });
  29385. }, function () {
  29386. //execution ended, run the success callback.
  29387. if (task.successCallback) {
  29388. task.successCallback();
  29389. }
  29390. _this.executeNext();
  29391. });
  29392. }
  29393. };
  29394. SimplificationQueue.prototype.getSimplifier = function (task) {
  29395. switch (task.simplificationType) {
  29396. case SimplificationType.QUADRATIC:
  29397. default:
  29398. return new QuadraticErrorSimplification(task.mesh);
  29399. }
  29400. };
  29401. return SimplificationQueue;
  29402. })();
  29403. BABYLON.SimplificationQueue = SimplificationQueue;
  29404. /**
  29405. * The implemented types of simplification.
  29406. * At the moment only Quadratic Error Decimation is implemented.
  29407. */
  29408. (function (SimplificationType) {
  29409. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29410. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29411. var SimplificationType = BABYLON.SimplificationType;
  29412. var DecimationTriangle = (function () {
  29413. function DecimationTriangle(vertices) {
  29414. this.vertices = vertices;
  29415. this.error = new Array(4);
  29416. this.deleted = false;
  29417. this.isDirty = false;
  29418. this.deletePending = false;
  29419. this.borderFactor = 0;
  29420. }
  29421. return DecimationTriangle;
  29422. })();
  29423. BABYLON.DecimationTriangle = DecimationTriangle;
  29424. var DecimationVertex = (function () {
  29425. function DecimationVertex(position, id) {
  29426. this.position = position;
  29427. this.id = id;
  29428. this.isBorder = true;
  29429. this.q = new QuadraticMatrix();
  29430. this.triangleCount = 0;
  29431. this.triangleStart = 0;
  29432. this.originalOffsets = [];
  29433. }
  29434. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29435. this.position.copyFrom(newPosition);
  29436. };
  29437. return DecimationVertex;
  29438. })();
  29439. BABYLON.DecimationVertex = DecimationVertex;
  29440. var QuadraticMatrix = (function () {
  29441. function QuadraticMatrix(data) {
  29442. this.data = new Array(10);
  29443. for (var i = 0; i < 10; ++i) {
  29444. if (data && data[i]) {
  29445. this.data[i] = data[i];
  29446. }
  29447. else {
  29448. this.data[i] = 0;
  29449. }
  29450. }
  29451. }
  29452. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29453. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29454. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29455. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29456. return det;
  29457. };
  29458. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29459. for (var i = 0; i < 10; ++i) {
  29460. this.data[i] += matrix.data[i];
  29461. }
  29462. };
  29463. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29464. for (var i = 0; i < 10; ++i) {
  29465. this.data[i] += data[i];
  29466. }
  29467. };
  29468. QuadraticMatrix.prototype.add = function (matrix) {
  29469. var m = new QuadraticMatrix();
  29470. for (var i = 0; i < 10; ++i) {
  29471. m.data[i] = this.data[i] + matrix.data[i];
  29472. }
  29473. return m;
  29474. };
  29475. QuadraticMatrix.FromData = function (a, b, c, d) {
  29476. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29477. };
  29478. //returning an array to avoid garbage collection
  29479. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29480. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29481. };
  29482. return QuadraticMatrix;
  29483. })();
  29484. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29485. var Reference = (function () {
  29486. function Reference(vertexId, triangleId) {
  29487. this.vertexId = vertexId;
  29488. this.triangleId = triangleId;
  29489. }
  29490. return Reference;
  29491. })();
  29492. BABYLON.Reference = Reference;
  29493. /**
  29494. * An implementation of the Quadratic Error simplification algorithm.
  29495. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29496. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29497. * @author RaananW
  29498. */
  29499. var QuadraticErrorSimplification = (function () {
  29500. function QuadraticErrorSimplification(_mesh) {
  29501. this._mesh = _mesh;
  29502. this.initialized = false;
  29503. this.syncIterations = 5000;
  29504. this.aggressiveness = 7;
  29505. this.decimationIterations = 100;
  29506. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29507. }
  29508. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29509. var _this = this;
  29510. this.initDecimatedMesh();
  29511. //iterating through the submeshes array, one after the other.
  29512. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29513. _this.initWithMesh(loop.index, function () {
  29514. _this.runDecimation(settings, loop.index, function () {
  29515. loop.executeNext();
  29516. });
  29517. }, settings.optimizeMesh);
  29518. }, function () {
  29519. setTimeout(function () {
  29520. successCallback(_this._reconstructedMesh);
  29521. }, 0);
  29522. });
  29523. };
  29524. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29525. var _this = this;
  29526. var gCount = 0;
  29527. triangle.vertices.forEach(function (vertex) {
  29528. var count = 0;
  29529. var vPos = vertex.position;
  29530. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29531. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29532. ++count;
  29533. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29534. ++count;
  29535. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29536. ++count;
  29537. if (count > 1) {
  29538. ++gCount;
  29539. }
  29540. ;
  29541. });
  29542. if (gCount > 1) {
  29543. console.log(triangle, gCount);
  29544. }
  29545. return gCount > 1;
  29546. };
  29547. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29548. var _this = this;
  29549. var targetCount = ~~(this.triangles.length * settings.quality);
  29550. var deletedTriangles = 0;
  29551. var triangleCount = this.triangles.length;
  29552. var iterationFunction = function (iteration, callback) {
  29553. setTimeout(function () {
  29554. if (iteration % 5 === 0) {
  29555. _this.updateMesh(iteration === 0);
  29556. }
  29557. for (var i = 0; i < _this.triangles.length; ++i) {
  29558. _this.triangles[i].isDirty = false;
  29559. }
  29560. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29561. var trianglesIterator = function (i) {
  29562. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29563. var t = _this.triangles[tIdx];
  29564. if (!t)
  29565. return;
  29566. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29567. return;
  29568. }
  29569. for (var j = 0; j < 3; ++j) {
  29570. if (t.error[j] < threshold) {
  29571. var deleted0 = [];
  29572. var deleted1 = [];
  29573. var v0 = t.vertices[j];
  29574. var v1 = t.vertices[(j + 1) % 3];
  29575. if (v0.isBorder !== v1.isBorder)
  29576. continue;
  29577. var p = BABYLON.Vector3.Zero();
  29578. var n = BABYLON.Vector3.Zero();
  29579. var uv = BABYLON.Vector2.Zero();
  29580. var color = new BABYLON.Color4(0, 0, 0, 1);
  29581. _this.calculateError(v0, v1, p, n, uv, color);
  29582. var delTr = [];
  29583. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29584. continue;
  29585. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29586. continue;
  29587. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29588. continue;
  29589. var uniqueArray = [];
  29590. delTr.forEach(function (deletedT) {
  29591. if (uniqueArray.indexOf(deletedT) === -1) {
  29592. deletedT.deletePending = true;
  29593. uniqueArray.push(deletedT);
  29594. }
  29595. });
  29596. if (uniqueArray.length % 2 !== 0) {
  29597. continue;
  29598. }
  29599. v0.q = v1.q.add(v0.q);
  29600. v0.updatePosition(p);
  29601. var tStart = _this.references.length;
  29602. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29603. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29604. var tCount = _this.references.length - tStart;
  29605. if (tCount <= v0.triangleCount) {
  29606. if (tCount) {
  29607. for (var c = 0; c < tCount; c++) {
  29608. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29609. }
  29610. }
  29611. }
  29612. else {
  29613. v0.triangleStart = tStart;
  29614. }
  29615. v0.triangleCount = tCount;
  29616. break;
  29617. }
  29618. }
  29619. };
  29620. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29621. }, 0);
  29622. };
  29623. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29624. if (triangleCount - deletedTriangles <= targetCount)
  29625. loop.breakLoop();
  29626. else {
  29627. iterationFunction(loop.index, function () {
  29628. loop.executeNext();
  29629. });
  29630. }
  29631. }, function () {
  29632. setTimeout(function () {
  29633. //reconstruct this part of the mesh
  29634. _this.reconstructMesh(submeshIndex);
  29635. successCallback();
  29636. }, 0);
  29637. });
  29638. };
  29639. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29640. var _this = this;
  29641. this.vertices = [];
  29642. this.triangles = [];
  29643. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29644. var indices = this._mesh.getIndices();
  29645. var submesh = this._mesh.subMeshes[submeshIndex];
  29646. var findInVertices = function (positionToSearch) {
  29647. if (optimizeMesh) {
  29648. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29649. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29650. return _this.vertices[ii];
  29651. }
  29652. }
  29653. }
  29654. return null;
  29655. };
  29656. var vertexReferences = [];
  29657. var vertexInit = function (i) {
  29658. var offset = i + submesh.verticesStart;
  29659. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29660. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29661. vertex.originalOffsets.push(offset);
  29662. if (vertex.id === _this.vertices.length) {
  29663. _this.vertices.push(vertex);
  29664. }
  29665. vertexReferences.push(vertex.id);
  29666. };
  29667. //var totalVertices = mesh.getTotalVertices();
  29668. var totalVertices = submesh.verticesCount;
  29669. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29670. var indicesInit = function (i) {
  29671. var offset = (submesh.indexStart / 3) + i;
  29672. var pos = (offset * 3);
  29673. var i0 = indices[pos + 0];
  29674. var i1 = indices[pos + 1];
  29675. var i2 = indices[pos + 2];
  29676. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29677. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29678. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29679. var triangle = new DecimationTriangle([v0, v1, v2]);
  29680. triangle.originalOffset = pos;
  29681. _this.triangles.push(triangle);
  29682. };
  29683. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29684. _this.init(callback);
  29685. });
  29686. });
  29687. };
  29688. QuadraticErrorSimplification.prototype.init = function (callback) {
  29689. var _this = this;
  29690. var triangleInit1 = function (i) {
  29691. var t = _this.triangles[i];
  29692. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29693. for (var j = 0; j < 3; j++) {
  29694. 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))));
  29695. }
  29696. };
  29697. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29698. var triangleInit2 = function (i) {
  29699. var t = _this.triangles[i];
  29700. for (var j = 0; j < 3; ++j) {
  29701. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29702. }
  29703. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29704. };
  29705. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29706. _this.initialized = true;
  29707. callback();
  29708. });
  29709. });
  29710. };
  29711. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29712. var newTriangles = [];
  29713. var i;
  29714. for (i = 0; i < this.vertices.length; ++i) {
  29715. this.vertices[i].triangleCount = 0;
  29716. }
  29717. var t;
  29718. var j;
  29719. for (i = 0; i < this.triangles.length; ++i) {
  29720. if (!this.triangles[i].deleted) {
  29721. t = this.triangles[i];
  29722. for (j = 0; j < 3; ++j) {
  29723. t.vertices[j].triangleCount = 1;
  29724. }
  29725. newTriangles.push(t);
  29726. }
  29727. }
  29728. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29729. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29730. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29731. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29732. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29733. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29734. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29735. var vertexCount = 0;
  29736. for (i = 0; i < this.vertices.length; ++i) {
  29737. var vertex = this.vertices[i];
  29738. vertex.id = vertexCount;
  29739. if (vertex.triangleCount) {
  29740. vertex.originalOffsets.forEach(function (originalOffset) {
  29741. newPositionData.push(vertex.position.x);
  29742. newPositionData.push(vertex.position.y);
  29743. newPositionData.push(vertex.position.z);
  29744. newNormalData.push(normalData[originalOffset * 3]);
  29745. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29746. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29747. if (uvs && uvs.length) {
  29748. newUVsData.push(uvs[(originalOffset * 2)]);
  29749. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29750. }
  29751. else if (colorsData && colorsData.length) {
  29752. newColorsData.push(colorsData[(originalOffset * 4)]);
  29753. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29754. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29755. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29756. }
  29757. ++vertexCount;
  29758. });
  29759. }
  29760. }
  29761. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29762. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29763. var submeshesArray = this._reconstructedMesh.subMeshes;
  29764. this._reconstructedMesh.subMeshes = [];
  29765. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29766. var originalIndices = this._mesh.getIndices();
  29767. for (i = 0; i < newTriangles.length; ++i) {
  29768. t = newTriangles[i]; //now get the new referencing point for each vertex
  29769. [0, 1, 2].forEach(function (idx) {
  29770. var id = originalIndices[t.originalOffset + idx];
  29771. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29772. if (offset < 0)
  29773. offset = 0;
  29774. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29775. });
  29776. }
  29777. //overwriting the old vertex buffers and indices.
  29778. this._reconstructedMesh.setIndices(newIndicesArray);
  29779. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29780. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29781. if (newUVsData.length > 0)
  29782. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29783. if (newColorsData.length > 0)
  29784. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29785. //create submesh
  29786. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29787. if (submeshIndex > 0) {
  29788. this._reconstructedMesh.subMeshes = [];
  29789. submeshesArray.forEach(function (submesh) {
  29790. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29791. });
  29792. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29793. }
  29794. };
  29795. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29796. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29797. this._reconstructedMesh.material = this._mesh.material;
  29798. this._reconstructedMesh.parent = this._mesh.parent;
  29799. this._reconstructedMesh.isVisible = false;
  29800. };
  29801. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29802. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29803. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29804. if (t.deleted)
  29805. continue;
  29806. var s = this.references[vertex1.triangleStart + i].vertexId;
  29807. var v1 = t.vertices[(s + 1) % 3];
  29808. var v2 = t.vertices[(s + 2) % 3];
  29809. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29810. deletedArray[i] = true;
  29811. delTr.push(t);
  29812. continue;
  29813. }
  29814. var d1 = v1.position.subtract(point);
  29815. d1 = d1.normalize();
  29816. var d2 = v2.position.subtract(point);
  29817. d2 = d2.normalize();
  29818. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29819. return true;
  29820. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29821. deletedArray[i] = false;
  29822. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29823. return true;
  29824. }
  29825. return false;
  29826. };
  29827. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29828. var newDeleted = deletedTriangles;
  29829. for (var i = 0; i < vertex.triangleCount; ++i) {
  29830. var ref = this.references[vertex.triangleStart + i];
  29831. var t = this.triangles[ref.triangleId];
  29832. if (t.deleted)
  29833. continue;
  29834. if (deletedArray[i] && t.deletePending) {
  29835. t.deleted = true;
  29836. newDeleted++;
  29837. continue;
  29838. }
  29839. t.vertices[ref.vertexId] = origVertex;
  29840. t.isDirty = true;
  29841. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29842. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29843. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29844. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29845. this.references.push(ref);
  29846. }
  29847. return newDeleted;
  29848. };
  29849. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29850. for (var i = 0; i < this.vertices.length; ++i) {
  29851. var vCount = [];
  29852. var vId = [];
  29853. var v = this.vertices[i];
  29854. var j;
  29855. for (j = 0; j < v.triangleCount; ++j) {
  29856. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29857. for (var ii = 0; ii < 3; ii++) {
  29858. var ofs = 0;
  29859. var vv = triangle.vertices[ii];
  29860. while (ofs < vCount.length) {
  29861. if (vId[ofs] === vv.id)
  29862. break;
  29863. ++ofs;
  29864. }
  29865. if (ofs === vCount.length) {
  29866. vCount.push(1);
  29867. vId.push(vv.id);
  29868. }
  29869. else {
  29870. vCount[ofs]++;
  29871. }
  29872. }
  29873. }
  29874. for (j = 0; j < vCount.length; ++j) {
  29875. if (vCount[j] === 1) {
  29876. this.vertices[vId[j]].isBorder = true;
  29877. }
  29878. else {
  29879. this.vertices[vId[j]].isBorder = false;
  29880. }
  29881. }
  29882. }
  29883. };
  29884. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29885. if (identifyBorders === void 0) { identifyBorders = false; }
  29886. var i;
  29887. if (!identifyBorders) {
  29888. var newTrianglesVector = [];
  29889. for (i = 0; i < this.triangles.length; ++i) {
  29890. if (!this.triangles[i].deleted) {
  29891. newTrianglesVector.push(this.triangles[i]);
  29892. }
  29893. }
  29894. this.triangles = newTrianglesVector;
  29895. }
  29896. for (i = 0; i < this.vertices.length; ++i) {
  29897. this.vertices[i].triangleCount = 0;
  29898. this.vertices[i].triangleStart = 0;
  29899. }
  29900. var t;
  29901. var j;
  29902. var v;
  29903. for (i = 0; i < this.triangles.length; ++i) {
  29904. t = this.triangles[i];
  29905. for (j = 0; j < 3; ++j) {
  29906. v = t.vertices[j];
  29907. v.triangleCount++;
  29908. }
  29909. }
  29910. var tStart = 0;
  29911. for (i = 0; i < this.vertices.length; ++i) {
  29912. this.vertices[i].triangleStart = tStart;
  29913. tStart += this.vertices[i].triangleCount;
  29914. this.vertices[i].triangleCount = 0;
  29915. }
  29916. var newReferences = new Array(this.triangles.length * 3);
  29917. for (i = 0; i < this.triangles.length; ++i) {
  29918. t = this.triangles[i];
  29919. for (j = 0; j < 3; ++j) {
  29920. v = t.vertices[j];
  29921. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29922. v.triangleCount++;
  29923. }
  29924. }
  29925. this.references = newReferences;
  29926. if (identifyBorders) {
  29927. this.identifyBorder();
  29928. }
  29929. };
  29930. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29931. var x = point.x;
  29932. var y = point.y;
  29933. var z = point.z;
  29934. 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
  29935. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29936. };
  29937. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29938. var q = vertex1.q.add(vertex2.q);
  29939. var border = vertex1.isBorder && vertex2.isBorder;
  29940. var error = 0;
  29941. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29942. if (qDet !== 0 && !border) {
  29943. if (!pointResult) {
  29944. pointResult = BABYLON.Vector3.Zero();
  29945. }
  29946. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29947. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29948. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29949. error = this.vertexError(q, pointResult);
  29950. }
  29951. else {
  29952. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29953. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29954. var error1 = this.vertexError(q, vertex1.position);
  29955. var error2 = this.vertexError(q, vertex2.position);
  29956. var error3 = this.vertexError(q, p3);
  29957. error = Math.min(error1, error2, error3);
  29958. if (error === error1) {
  29959. if (pointResult) {
  29960. pointResult.copyFrom(vertex1.position);
  29961. }
  29962. }
  29963. else if (error === error2) {
  29964. if (pointResult) {
  29965. pointResult.copyFrom(vertex2.position);
  29966. }
  29967. }
  29968. else {
  29969. if (pointResult) {
  29970. pointResult.copyFrom(p3);
  29971. }
  29972. }
  29973. }
  29974. return error;
  29975. };
  29976. return QuadraticErrorSimplification;
  29977. })();
  29978. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29979. })(BABYLON || (BABYLON = {}));
  29980. var BABYLON;
  29981. (function (BABYLON) {
  29982. var serializedGeometries = [];
  29983. var serializeGeometry = function (geometry, serializationGeometries) {
  29984. if (serializedGeometries[geometry.id]) {
  29985. return;
  29986. }
  29987. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29988. serializationGeometries.boxes.push(geometry.serialize());
  29989. }
  29990. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29991. serializationGeometries.spheres.push(geometry.serialize());
  29992. }
  29993. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29994. serializationGeometries.cylinders.push(geometry.serialize());
  29995. }
  29996. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29997. serializationGeometries.toruses.push(geometry.serialize());
  29998. }
  29999. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30000. serializationGeometries.grounds.push(geometry.serialize());
  30001. }
  30002. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30003. serializationGeometries.planes.push(geometry.serialize());
  30004. }
  30005. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30006. serializationGeometries.torusKnots.push(geometry.serialize());
  30007. }
  30008. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30009. throw new Error("Unknown primitive type");
  30010. }
  30011. else {
  30012. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30013. }
  30014. serializedGeometries[geometry.id] = true;
  30015. };
  30016. var serializeMesh = function (mesh, serializationScene) {
  30017. var serializationObject = {};
  30018. serializationObject.name = mesh.name;
  30019. serializationObject.id = mesh.id;
  30020. if (BABYLON.Tags.HasTags(mesh)) {
  30021. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30022. }
  30023. serializationObject.position = mesh.position.asArray();
  30024. if (mesh.rotationQuaternion) {
  30025. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30026. }
  30027. else if (mesh.rotation) {
  30028. serializationObject.rotation = mesh.rotation.asArray();
  30029. }
  30030. serializationObject.scaling = mesh.scaling.asArray();
  30031. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30032. serializationObject.isEnabled = mesh.isEnabled();
  30033. serializationObject.isVisible = mesh.isVisible;
  30034. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30035. serializationObject.pickable = mesh.isPickable;
  30036. serializationObject.receiveShadows = mesh.receiveShadows;
  30037. serializationObject.billboardMode = mesh.billboardMode;
  30038. serializationObject.visibility = mesh.visibility;
  30039. serializationObject.checkCollisions = mesh.checkCollisions;
  30040. // Parent
  30041. if (mesh.parent) {
  30042. serializationObject.parentId = mesh.parent.id;
  30043. }
  30044. // Geometry
  30045. var geometry = mesh._geometry;
  30046. if (geometry) {
  30047. var geometryId = geometry.id;
  30048. serializationObject.geometryId = geometryId;
  30049. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30050. // 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
  30051. serializeGeometry(geometry, serializationScene.geometries);
  30052. }
  30053. // SubMeshes
  30054. serializationObject.subMeshes = [];
  30055. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30056. var subMesh = mesh.subMeshes[subIndex];
  30057. serializationObject.subMeshes.push({
  30058. materialIndex: subMesh.materialIndex,
  30059. verticesStart: subMesh.verticesStart,
  30060. verticesCount: subMesh.verticesCount,
  30061. indexStart: subMesh.indexStart,
  30062. indexCount: subMesh.indexCount
  30063. });
  30064. }
  30065. }
  30066. // Material
  30067. if (mesh.material) {
  30068. serializationObject.materialId = mesh.material.id;
  30069. }
  30070. else {
  30071. mesh.material = null;
  30072. }
  30073. // Skeleton
  30074. if (mesh.skeleton) {
  30075. serializationObject.skeletonId = mesh.skeleton.id;
  30076. }
  30077. // Physics
  30078. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30079. serializationObject.physicsMass = mesh.getPhysicsMass();
  30080. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30081. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30082. switch (mesh.getPhysicsImpostor()) {
  30083. case BABYLON.PhysicsEngine.BoxImpostor:
  30084. serializationObject.physicsImpostor = 1;
  30085. break;
  30086. case BABYLON.PhysicsEngine.SphereImpostor:
  30087. serializationObject.physicsImpostor = 2;
  30088. break;
  30089. }
  30090. }
  30091. // Instances
  30092. serializationObject.instances = [];
  30093. for (var index = 0; index < mesh.instances.length; index++) {
  30094. var instance = mesh.instances[index];
  30095. var serializationInstance = {
  30096. name: instance.name,
  30097. position: instance.position.asArray(),
  30098. scaling: instance.scaling.asArray()
  30099. };
  30100. if (instance.rotationQuaternion) {
  30101. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30102. }
  30103. else if (instance.rotation) {
  30104. serializationInstance.rotation = instance.rotation.asArray();
  30105. }
  30106. serializationObject.instances.push(serializationInstance);
  30107. // Animations
  30108. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30109. }
  30110. // Animations
  30111. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30112. // Layer mask
  30113. serializationObject.layerMask = mesh.layerMask;
  30114. return serializationObject;
  30115. };
  30116. var finalizeSingleMesh = function (mesh, serializationObject) {
  30117. //only works if the mesh is already loaded
  30118. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30119. //serialize material
  30120. if (mesh.material) {
  30121. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30122. serializationObject.materials = serializationObject.materials || [];
  30123. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30124. serializationObject.materials.push(mesh.material.serialize());
  30125. }
  30126. }
  30127. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30128. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30129. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30130. serializationObject.multiMaterials.push(mesh.material.serialize());
  30131. }
  30132. }
  30133. }
  30134. //serialize geometry
  30135. var geometry = mesh._geometry;
  30136. if (geometry) {
  30137. if (!serializationObject.geometries) {
  30138. serializationObject.geometries = {};
  30139. serializationObject.geometries.boxes = [];
  30140. serializationObject.geometries.spheres = [];
  30141. serializationObject.geometries.cylinders = [];
  30142. serializationObject.geometries.toruses = [];
  30143. serializationObject.geometries.grounds = [];
  30144. serializationObject.geometries.planes = [];
  30145. serializationObject.geometries.torusKnots = [];
  30146. serializationObject.geometries.vertexData = [];
  30147. }
  30148. serializeGeometry(geometry, serializationObject.geometries);
  30149. }
  30150. // Skeletons
  30151. if (mesh.skeleton) {
  30152. serializationObject.skeletons = serializationObject.skeletons || [];
  30153. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30154. }
  30155. //serialize the actual mesh
  30156. serializationObject.meshes = serializationObject.meshes || [];
  30157. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30158. }
  30159. };
  30160. var SceneSerializer = (function () {
  30161. function SceneSerializer() {
  30162. }
  30163. SceneSerializer.Serialize = function (scene) {
  30164. var serializationObject = {};
  30165. // Scene
  30166. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30167. serializationObject.autoClear = scene.autoClear;
  30168. serializationObject.clearColor = scene.clearColor.asArray();
  30169. serializationObject.ambientColor = scene.ambientColor.asArray();
  30170. serializationObject.gravity = scene.gravity.asArray();
  30171. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30172. serializationObject.workerCollisions = scene.workerCollisions;
  30173. // Fog
  30174. if (scene.fogMode && scene.fogMode !== 0) {
  30175. serializationObject.fogMode = scene.fogMode;
  30176. serializationObject.fogColor = scene.fogColor.asArray();
  30177. serializationObject.fogStart = scene.fogStart;
  30178. serializationObject.fogEnd = scene.fogEnd;
  30179. serializationObject.fogDensity = scene.fogDensity;
  30180. }
  30181. //Physics
  30182. if (scene.isPhysicsEnabled()) {
  30183. serializationObject.physicsEnabled = true;
  30184. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30185. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30186. }
  30187. // Lights
  30188. serializationObject.lights = [];
  30189. var index;
  30190. var light;
  30191. for (index = 0; index < scene.lights.length; index++) {
  30192. light = scene.lights[index];
  30193. serializationObject.lights.push(light.serialize());
  30194. }
  30195. // Cameras
  30196. serializationObject.cameras = [];
  30197. for (index = 0; index < scene.cameras.length; index++) {
  30198. var camera = scene.cameras[index];
  30199. serializationObject.cameras.push(camera.serialize());
  30200. }
  30201. if (scene.activeCamera) {
  30202. serializationObject.activeCameraID = scene.activeCamera.id;
  30203. }
  30204. // Materials
  30205. serializationObject.materials = [];
  30206. serializationObject.multiMaterials = [];
  30207. var material;
  30208. for (index = 0; index < scene.materials.length; index++) {
  30209. material = scene.materials[index];
  30210. serializationObject.materials.push(material.serialize());
  30211. }
  30212. // MultiMaterials
  30213. serializationObject.multiMaterials = [];
  30214. for (index = 0; index < scene.multiMaterials.length; index++) {
  30215. var multiMaterial = scene.multiMaterials[index];
  30216. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30217. }
  30218. // Skeletons
  30219. serializationObject.skeletons = [];
  30220. for (index = 0; index < scene.skeletons.length; index++) {
  30221. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30222. }
  30223. // Geometries
  30224. serializationObject.geometries = {};
  30225. serializationObject.geometries.boxes = [];
  30226. serializationObject.geometries.spheres = [];
  30227. serializationObject.geometries.cylinders = [];
  30228. serializationObject.geometries.toruses = [];
  30229. serializationObject.geometries.grounds = [];
  30230. serializationObject.geometries.planes = [];
  30231. serializationObject.geometries.torusKnots = [];
  30232. serializationObject.geometries.vertexData = [];
  30233. serializedGeometries = [];
  30234. var geometries = scene.getGeometries();
  30235. for (index = 0; index < geometries.length; index++) {
  30236. var geometry = geometries[index];
  30237. if (geometry.isReady()) {
  30238. serializeGeometry(geometry, serializationObject.geometries);
  30239. }
  30240. }
  30241. // Meshes
  30242. serializationObject.meshes = [];
  30243. for (index = 0; index < scene.meshes.length; index++) {
  30244. var abstractMesh = scene.meshes[index];
  30245. if (abstractMesh instanceof BABYLON.Mesh) {
  30246. var mesh = abstractMesh;
  30247. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30248. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30249. }
  30250. }
  30251. }
  30252. // Particles Systems
  30253. serializationObject.particleSystems = [];
  30254. for (index = 0; index < scene.particleSystems.length; index++) {
  30255. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30256. }
  30257. // Lens flares
  30258. serializationObject.lensFlareSystems = [];
  30259. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30260. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30261. }
  30262. // Shadows
  30263. serializationObject.shadowGenerators = [];
  30264. for (index = 0; index < scene.lights.length; index++) {
  30265. light = scene.lights[index];
  30266. if (light.getShadowGenerator()) {
  30267. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30268. }
  30269. }
  30270. return serializationObject;
  30271. };
  30272. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30273. if (withParents === void 0) { withParents = false; }
  30274. if (withChildren === void 0) { withChildren = false; }
  30275. var serializationObject = {};
  30276. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30277. if (withParents || withChildren) {
  30278. //deliberate for loop! not for each, appended should be processed as well.
  30279. for (var i = 0; i < toSerialize.length; ++i) {
  30280. if (withChildren) {
  30281. toSerialize[i].getDescendants().forEach(function (node) {
  30282. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30283. toSerialize.push(node);
  30284. }
  30285. });
  30286. }
  30287. //make sure the array doesn't contain the object already
  30288. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30289. toSerialize.push(toSerialize[i].parent);
  30290. }
  30291. }
  30292. }
  30293. toSerialize.forEach(function (mesh) {
  30294. finalizeSingleMesh(mesh, serializationObject);
  30295. });
  30296. return serializationObject;
  30297. };
  30298. return SceneSerializer;
  30299. })();
  30300. BABYLON.SceneSerializer = SceneSerializer;
  30301. })(BABYLON || (BABYLON = {}));
  30302. var BABYLON;
  30303. (function (BABYLON) {
  30304. // Unique ID when we import meshes from Babylon to CSG
  30305. var currentCSGMeshId = 0;
  30306. // # class Vertex
  30307. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30308. // one to provide additional features like texture coordinates and vertex
  30309. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30310. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30311. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30312. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30313. // is not used anywhere else.
  30314. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30315. var Vertex = (function () {
  30316. function Vertex(pos, normal, uv) {
  30317. this.pos = pos;
  30318. this.normal = normal;
  30319. this.uv = uv;
  30320. }
  30321. Vertex.prototype.clone = function () {
  30322. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30323. };
  30324. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30325. // orientation of a polygon is flipped.
  30326. Vertex.prototype.flip = function () {
  30327. this.normal = this.normal.scale(-1);
  30328. };
  30329. // Create a new vertex between this vertex and `other` by linearly
  30330. // interpolating all properties using a parameter of `t`. Subclasses should
  30331. // override this to interpolate additional properties.
  30332. Vertex.prototype.interpolate = function (other, t) {
  30333. 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));
  30334. };
  30335. return Vertex;
  30336. })();
  30337. // # class Plane
  30338. // Represents a plane in 3D space.
  30339. var Plane = (function () {
  30340. function Plane(normal, w) {
  30341. this.normal = normal;
  30342. this.w = w;
  30343. }
  30344. Plane.FromPoints = function (a, b, c) {
  30345. var v0 = c.subtract(a);
  30346. var v1 = b.subtract(a);
  30347. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30348. return null;
  30349. }
  30350. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30351. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30352. };
  30353. Plane.prototype.clone = function () {
  30354. return new Plane(this.normal.clone(), this.w);
  30355. };
  30356. Plane.prototype.flip = function () {
  30357. this.normal.scaleInPlace(-1);
  30358. this.w = -this.w;
  30359. };
  30360. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30361. // fragments in the appropriate lists. Coplanar polygons go into either
  30362. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30363. // respect to this plane. Polygons in front or in back of this plane go into
  30364. // either `front` or `back`.
  30365. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30366. var COPLANAR = 0;
  30367. var FRONT = 1;
  30368. var BACK = 2;
  30369. var SPANNING = 3;
  30370. // Classify each point as well as the entire polygon into one of the above
  30371. // four classes.
  30372. var polygonType = 0;
  30373. var types = [];
  30374. var i;
  30375. var t;
  30376. for (i = 0; i < polygon.vertices.length; i++) {
  30377. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30378. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30379. polygonType |= type;
  30380. types.push(type);
  30381. }
  30382. // Put the polygon in the correct list, splitting it when necessary.
  30383. switch (polygonType) {
  30384. case COPLANAR:
  30385. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30386. break;
  30387. case FRONT:
  30388. front.push(polygon);
  30389. break;
  30390. case BACK:
  30391. back.push(polygon);
  30392. break;
  30393. case SPANNING:
  30394. var f = [], b = [];
  30395. for (i = 0; i < polygon.vertices.length; i++) {
  30396. var j = (i + 1) % polygon.vertices.length;
  30397. var ti = types[i], tj = types[j];
  30398. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30399. if (ti !== BACK)
  30400. f.push(vi);
  30401. if (ti !== FRONT)
  30402. b.push(ti !== BACK ? vi.clone() : vi);
  30403. if ((ti | tj) === SPANNING) {
  30404. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30405. var v = vi.interpolate(vj, t);
  30406. f.push(v);
  30407. b.push(v.clone());
  30408. }
  30409. }
  30410. var poly;
  30411. if (f.length >= 3) {
  30412. poly = new Polygon(f, polygon.shared);
  30413. if (poly.plane)
  30414. front.push(poly);
  30415. }
  30416. if (b.length >= 3) {
  30417. poly = new Polygon(b, polygon.shared);
  30418. if (poly.plane)
  30419. back.push(poly);
  30420. }
  30421. break;
  30422. }
  30423. };
  30424. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30425. // point is on the plane.
  30426. Plane.EPSILON = 1e-5;
  30427. return Plane;
  30428. })();
  30429. // # class Polygon
  30430. // Represents a convex polygon. The vertices used to initialize a polygon must
  30431. // be coplanar and form a convex loop.
  30432. //
  30433. // Each convex polygon has a `shared` property, which is shared between all
  30434. // polygons that are clones of each other or were split from the same polygon.
  30435. // This can be used to define per-polygon properties (such as surface color).
  30436. var Polygon = (function () {
  30437. function Polygon(vertices, shared) {
  30438. this.vertices = vertices;
  30439. this.shared = shared;
  30440. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30441. }
  30442. Polygon.prototype.clone = function () {
  30443. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30444. return new Polygon(vertices, this.shared);
  30445. };
  30446. Polygon.prototype.flip = function () {
  30447. this.vertices.reverse().map(function (v) { v.flip(); });
  30448. this.plane.flip();
  30449. };
  30450. return Polygon;
  30451. })();
  30452. // # class Node
  30453. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30454. // by picking a polygon to split along. That polygon (and all other coplanar
  30455. // polygons) are added directly to that node and the other polygons are added to
  30456. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30457. // no distinction between internal and leaf nodes.
  30458. var Node = (function () {
  30459. function Node(polygons) {
  30460. this.plane = null;
  30461. this.front = null;
  30462. this.back = null;
  30463. this.polygons = [];
  30464. if (polygons) {
  30465. this.build(polygons);
  30466. }
  30467. }
  30468. Node.prototype.clone = function () {
  30469. var node = new Node();
  30470. node.plane = this.plane && this.plane.clone();
  30471. node.front = this.front && this.front.clone();
  30472. node.back = this.back && this.back.clone();
  30473. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30474. return node;
  30475. };
  30476. // Convert solid space to empty space and empty space to solid space.
  30477. Node.prototype.invert = function () {
  30478. for (var i = 0; i < this.polygons.length; i++) {
  30479. this.polygons[i].flip();
  30480. }
  30481. if (this.plane) {
  30482. this.plane.flip();
  30483. }
  30484. if (this.front) {
  30485. this.front.invert();
  30486. }
  30487. if (this.back) {
  30488. this.back.invert();
  30489. }
  30490. var temp = this.front;
  30491. this.front = this.back;
  30492. this.back = temp;
  30493. };
  30494. // Recursively remove all polygons in `polygons` that are inside this BSP
  30495. // tree.
  30496. Node.prototype.clipPolygons = function (polygons) {
  30497. if (!this.plane)
  30498. return polygons.slice();
  30499. var front = [], back = [];
  30500. for (var i = 0; i < polygons.length; i++) {
  30501. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30502. }
  30503. if (this.front) {
  30504. front = this.front.clipPolygons(front);
  30505. }
  30506. if (this.back) {
  30507. back = this.back.clipPolygons(back);
  30508. }
  30509. else {
  30510. back = [];
  30511. }
  30512. return front.concat(back);
  30513. };
  30514. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30515. // `bsp`.
  30516. Node.prototype.clipTo = function (bsp) {
  30517. this.polygons = bsp.clipPolygons(this.polygons);
  30518. if (this.front)
  30519. this.front.clipTo(bsp);
  30520. if (this.back)
  30521. this.back.clipTo(bsp);
  30522. };
  30523. // Return a list of all polygons in this BSP tree.
  30524. Node.prototype.allPolygons = function () {
  30525. var polygons = this.polygons.slice();
  30526. if (this.front)
  30527. polygons = polygons.concat(this.front.allPolygons());
  30528. if (this.back)
  30529. polygons = polygons.concat(this.back.allPolygons());
  30530. return polygons;
  30531. };
  30532. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30533. // new polygons are filtered down to the bottom of the tree and become new
  30534. // nodes there. Each set of polygons is partitioned using the first polygon
  30535. // (no heuristic is used to pick a good split).
  30536. Node.prototype.build = function (polygons) {
  30537. if (!polygons.length)
  30538. return;
  30539. if (!this.plane)
  30540. this.plane = polygons[0].plane.clone();
  30541. var front = [], back = [];
  30542. for (var i = 0; i < polygons.length; i++) {
  30543. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30544. }
  30545. if (front.length) {
  30546. if (!this.front)
  30547. this.front = new Node();
  30548. this.front.build(front);
  30549. }
  30550. if (back.length) {
  30551. if (!this.back)
  30552. this.back = new Node();
  30553. this.back.build(back);
  30554. }
  30555. };
  30556. return Node;
  30557. })();
  30558. var CSG = (function () {
  30559. function CSG() {
  30560. this.polygons = new Array();
  30561. }
  30562. // Convert BABYLON.Mesh to BABYLON.CSG
  30563. CSG.FromMesh = function (mesh) {
  30564. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30565. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30566. if (mesh instanceof BABYLON.Mesh) {
  30567. mesh.computeWorldMatrix(true);
  30568. matrix = mesh.getWorldMatrix();
  30569. meshPosition = mesh.position.clone();
  30570. meshRotation = mesh.rotation.clone();
  30571. if (mesh.rotationQuaternion) {
  30572. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30573. }
  30574. meshScaling = mesh.scaling.clone();
  30575. }
  30576. else {
  30577. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30578. }
  30579. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30580. var subMeshes = mesh.subMeshes;
  30581. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30582. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30583. vertices = [];
  30584. for (var j = 0; j < 3; j++) {
  30585. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30586. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30587. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30588. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30589. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30590. vertex = new Vertex(position, normal, uv);
  30591. vertices.push(vertex);
  30592. }
  30593. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30594. // To handle the case of degenerated triangle
  30595. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30596. if (polygon.plane)
  30597. polygons.push(polygon);
  30598. }
  30599. }
  30600. var csg = CSG.FromPolygons(polygons);
  30601. csg.matrix = matrix;
  30602. csg.position = meshPosition;
  30603. csg.rotation = meshRotation;
  30604. csg.scaling = meshScaling;
  30605. csg.rotationQuaternion = meshRotationQuaternion;
  30606. currentCSGMeshId++;
  30607. return csg;
  30608. };
  30609. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30610. CSG.FromPolygons = function (polygons) {
  30611. var csg = new CSG();
  30612. csg.polygons = polygons;
  30613. return csg;
  30614. };
  30615. CSG.prototype.clone = function () {
  30616. var csg = new CSG();
  30617. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30618. csg.copyTransformAttributes(this);
  30619. return csg;
  30620. };
  30621. CSG.prototype.toPolygons = function () {
  30622. return this.polygons;
  30623. };
  30624. CSG.prototype.union = function (csg) {
  30625. var a = new Node(this.clone().polygons);
  30626. var b = new Node(csg.clone().polygons);
  30627. a.clipTo(b);
  30628. b.clipTo(a);
  30629. b.invert();
  30630. b.clipTo(a);
  30631. b.invert();
  30632. a.build(b.allPolygons());
  30633. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30634. };
  30635. CSG.prototype.unionInPlace = function (csg) {
  30636. var a = new Node(this.polygons);
  30637. var b = new Node(csg.polygons);
  30638. a.clipTo(b);
  30639. b.clipTo(a);
  30640. b.invert();
  30641. b.clipTo(a);
  30642. b.invert();
  30643. a.build(b.allPolygons());
  30644. this.polygons = a.allPolygons();
  30645. };
  30646. CSG.prototype.subtract = function (csg) {
  30647. var a = new Node(this.clone().polygons);
  30648. var b = new Node(csg.clone().polygons);
  30649. a.invert();
  30650. a.clipTo(b);
  30651. b.clipTo(a);
  30652. b.invert();
  30653. b.clipTo(a);
  30654. b.invert();
  30655. a.build(b.allPolygons());
  30656. a.invert();
  30657. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30658. };
  30659. CSG.prototype.subtractInPlace = function (csg) {
  30660. var a = new Node(this.polygons);
  30661. var b = new Node(csg.polygons);
  30662. a.invert();
  30663. a.clipTo(b);
  30664. b.clipTo(a);
  30665. b.invert();
  30666. b.clipTo(a);
  30667. b.invert();
  30668. a.build(b.allPolygons());
  30669. a.invert();
  30670. this.polygons = a.allPolygons();
  30671. };
  30672. CSG.prototype.intersect = function (csg) {
  30673. var a = new Node(this.clone().polygons);
  30674. var b = new Node(csg.clone().polygons);
  30675. a.invert();
  30676. b.clipTo(a);
  30677. b.invert();
  30678. a.clipTo(b);
  30679. b.clipTo(a);
  30680. a.build(b.allPolygons());
  30681. a.invert();
  30682. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30683. };
  30684. CSG.prototype.intersectInPlace = function (csg) {
  30685. var a = new Node(this.polygons);
  30686. var b = new Node(csg.polygons);
  30687. a.invert();
  30688. b.clipTo(a);
  30689. b.invert();
  30690. a.clipTo(b);
  30691. b.clipTo(a);
  30692. a.build(b.allPolygons());
  30693. a.invert();
  30694. this.polygons = a.allPolygons();
  30695. };
  30696. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30697. // not modified.
  30698. CSG.prototype.inverse = function () {
  30699. var csg = this.clone();
  30700. csg.inverseInPlace();
  30701. return csg;
  30702. };
  30703. CSG.prototype.inverseInPlace = function () {
  30704. this.polygons.map(function (p) { p.flip(); });
  30705. };
  30706. // This is used to keep meshes transformations so they can be restored
  30707. // when we build back a Babylon Mesh
  30708. // NB : All CSG operations are performed in world coordinates
  30709. CSG.prototype.copyTransformAttributes = function (csg) {
  30710. this.matrix = csg.matrix;
  30711. this.position = csg.position;
  30712. this.rotation = csg.rotation;
  30713. this.scaling = csg.scaling;
  30714. this.rotationQuaternion = csg.rotationQuaternion;
  30715. return this;
  30716. };
  30717. // Build Raw mesh from CSG
  30718. // Coordinates here are in world space
  30719. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30720. var matrix = this.matrix.clone();
  30721. matrix.invert();
  30722. 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;
  30723. if (keepSubMeshes) {
  30724. // Sort Polygons, since subMeshes are indices range
  30725. polygons.sort(function (a, b) {
  30726. if (a.shared.meshId === b.shared.meshId) {
  30727. return a.shared.subMeshId - b.shared.subMeshId;
  30728. }
  30729. else {
  30730. return a.shared.meshId - b.shared.meshId;
  30731. }
  30732. });
  30733. }
  30734. for (var i = 0, il = polygons.length; i < il; i++) {
  30735. polygon = polygons[i];
  30736. // Building SubMeshes
  30737. if (!subMesh_dict[polygon.shared.meshId]) {
  30738. subMesh_dict[polygon.shared.meshId] = {};
  30739. }
  30740. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30741. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30742. indexStart: +Infinity,
  30743. indexEnd: -Infinity,
  30744. materialIndex: polygon.shared.materialIndex
  30745. };
  30746. }
  30747. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30748. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30749. polygonIndices[0] = 0;
  30750. polygonIndices[1] = j - 1;
  30751. polygonIndices[2] = j;
  30752. for (var k = 0; k < 3; k++) {
  30753. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30754. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30755. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30756. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30757. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30758. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30759. // Check if 2 points can be merged
  30760. if (!(typeof vertex_idx !== 'undefined' &&
  30761. normals[vertex_idx * 3] === localNormal.x &&
  30762. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30763. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30764. uvs[vertex_idx * 2] === uv.x &&
  30765. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30766. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30767. uvs.push(uv.x, uv.y);
  30768. normals.push(normal.x, normal.y, normal.z);
  30769. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30770. }
  30771. indices.push(vertex_idx);
  30772. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30773. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30774. currentIndex++;
  30775. }
  30776. }
  30777. }
  30778. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30779. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30780. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30781. mesh.setIndices(indices);
  30782. if (keepSubMeshes) {
  30783. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30784. var materialIndexOffset = 0, materialMaxIndex;
  30785. mesh.subMeshes = new Array();
  30786. for (var m in subMesh_dict) {
  30787. materialMaxIndex = -1;
  30788. for (var sm in subMesh_dict[m]) {
  30789. subMesh_obj = subMesh_dict[m][sm];
  30790. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30791. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30792. }
  30793. materialIndexOffset += ++materialMaxIndex;
  30794. }
  30795. }
  30796. return mesh;
  30797. };
  30798. // Build Mesh from CSG taking material and transforms into account
  30799. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30800. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30801. mesh.material = material;
  30802. mesh.position.copyFrom(this.position);
  30803. mesh.rotation.copyFrom(this.rotation);
  30804. if (this.rotationQuaternion) {
  30805. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30806. }
  30807. mesh.scaling.copyFrom(this.scaling);
  30808. mesh.computeWorldMatrix(true);
  30809. return mesh;
  30810. };
  30811. return CSG;
  30812. })();
  30813. BABYLON.CSG = CSG;
  30814. })(BABYLON || (BABYLON = {}));
  30815. var BABYLON;
  30816. (function (BABYLON) {
  30817. var VRDistortionCorrectionPostProcess = (function (_super) {
  30818. __extends(VRDistortionCorrectionPostProcess, _super);
  30819. //ANY
  30820. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30821. var _this = this;
  30822. _super.call(this, name, "vrDistortionCorrection", [
  30823. 'LensCenter',
  30824. 'Scale',
  30825. 'ScaleIn',
  30826. 'HmdWarpParam'
  30827. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30828. this._isRightEye = isRightEye;
  30829. this._distortionFactors = vrMetrics.distortionK;
  30830. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30831. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30832. this.onSizeChanged = function () {
  30833. _this.aspectRatio = _this.width * .5 / _this.height;
  30834. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30835. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30836. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30837. };
  30838. this.onApply = function (effect) {
  30839. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30840. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30841. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30842. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30843. };
  30844. }
  30845. return VRDistortionCorrectionPostProcess;
  30846. })(BABYLON.PostProcess);
  30847. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30848. })(BABYLON || (BABYLON = {}));
  30849. // Mainly based on these 2 articles :
  30850. // 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
  30851. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30852. var BABYLON;
  30853. (function (BABYLON) {
  30854. (function (JoystickAxis) {
  30855. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30856. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30857. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30858. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30859. var JoystickAxis = BABYLON.JoystickAxis;
  30860. var VirtualJoystick = (function () {
  30861. function VirtualJoystick(leftJoystick) {
  30862. var _this = this;
  30863. if (leftJoystick) {
  30864. this._leftJoystick = true;
  30865. }
  30866. else {
  30867. this._leftJoystick = false;
  30868. }
  30869. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30870. VirtualJoystick._globalJoystickIndex++;
  30871. // By default left & right arrow keys are moving the X
  30872. // and up & down keys are moving the Y
  30873. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30874. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30875. this.reverseLeftRight = false;
  30876. this.reverseUpDown = false;
  30877. // collections of pointers
  30878. this._touches = new BABYLON.SmartCollection();
  30879. this.deltaPosition = BABYLON.Vector3.Zero();
  30880. this._joystickSensibility = 25;
  30881. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30882. this._rotationSpeed = 25;
  30883. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30884. this._rotateOnAxisRelativeToMesh = false;
  30885. this._onResize = function (evt) {
  30886. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30887. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30888. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30889. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30890. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30891. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30892. };
  30893. // injecting a canvas element on top of the canvas 3D game
  30894. if (!VirtualJoystick.vjCanvas) {
  30895. window.addEventListener("resize", this._onResize, false);
  30896. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30897. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30898. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30899. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30900. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30901. VirtualJoystick.vjCanvas.style.width = "100%";
  30902. VirtualJoystick.vjCanvas.style.height = "100%";
  30903. VirtualJoystick.vjCanvas.style.position = "absolute";
  30904. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30905. VirtualJoystick.vjCanvas.style.top = "0px";
  30906. VirtualJoystick.vjCanvas.style.left = "0px";
  30907. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30908. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30909. // Support for jQuery PEP polyfill
  30910. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30911. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30912. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30913. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30914. document.body.appendChild(VirtualJoystick.vjCanvas);
  30915. }
  30916. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30917. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30918. this.pressed = false;
  30919. // default joystick color
  30920. this._joystickColor = "cyan";
  30921. this._joystickPointerID = -1;
  30922. // current joystick position
  30923. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30924. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30925. // origin joystick position
  30926. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30927. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30928. this._onPointerDownHandlerRef = function (evt) {
  30929. _this._onPointerDown(evt);
  30930. };
  30931. this._onPointerMoveHandlerRef = function (evt) {
  30932. _this._onPointerMove(evt);
  30933. };
  30934. this._onPointerOutHandlerRef = function (evt) {
  30935. _this._onPointerUp(evt);
  30936. };
  30937. this._onPointerUpHandlerRef = function (evt) {
  30938. _this._onPointerUp(evt);
  30939. };
  30940. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30941. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30942. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30943. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30944. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30945. evt.preventDefault(); // Disables system menu
  30946. }, false);
  30947. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30948. }
  30949. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30950. this._joystickSensibility = newJoystickSensibility;
  30951. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30952. };
  30953. VirtualJoystick.prototype._onPointerDown = function (e) {
  30954. var positionOnScreenCondition;
  30955. e.preventDefault();
  30956. if (this._leftJoystick === true) {
  30957. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30958. }
  30959. else {
  30960. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30961. }
  30962. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30963. // First contact will be dedicated to the virtual joystick
  30964. this._joystickPointerID = e.pointerId;
  30965. this._joystickPointerStartPos.x = e.clientX;
  30966. this._joystickPointerStartPos.y = e.clientY;
  30967. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30968. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30969. this._deltaJoystickVector.x = 0;
  30970. this._deltaJoystickVector.y = 0;
  30971. this.pressed = true;
  30972. this._touches.add(e.pointerId.toString(), e);
  30973. }
  30974. else {
  30975. // You can only trigger the action buttons with a joystick declared
  30976. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30977. this._action();
  30978. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30979. }
  30980. }
  30981. };
  30982. VirtualJoystick.prototype._onPointerMove = function (e) {
  30983. // If the current pointer is the one associated to the joystick (first touch contact)
  30984. if (this._joystickPointerID == e.pointerId) {
  30985. this._joystickPointerPos.x = e.clientX;
  30986. this._joystickPointerPos.y = e.clientY;
  30987. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30988. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30989. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30990. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30991. switch (this._axisTargetedByLeftAndRight) {
  30992. case JoystickAxis.X:
  30993. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30994. break;
  30995. case JoystickAxis.Y:
  30996. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30997. break;
  30998. case JoystickAxis.Z:
  30999. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31000. break;
  31001. }
  31002. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31003. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31004. switch (this._axisTargetedByUpAndDown) {
  31005. case JoystickAxis.X:
  31006. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31007. break;
  31008. case JoystickAxis.Y:
  31009. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31010. break;
  31011. case JoystickAxis.Z:
  31012. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31013. break;
  31014. }
  31015. }
  31016. else {
  31017. if (this._touches.item(e.pointerId.toString())) {
  31018. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31019. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31020. }
  31021. }
  31022. };
  31023. VirtualJoystick.prototype._onPointerUp = function (e) {
  31024. if (this._joystickPointerID == e.pointerId) {
  31025. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31026. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31027. this._joystickPointerID = -1;
  31028. this.pressed = false;
  31029. }
  31030. else {
  31031. var touch = this._touches.item(e.pointerId.toString());
  31032. if (touch) {
  31033. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31034. }
  31035. }
  31036. this._deltaJoystickVector.x = 0;
  31037. this._deltaJoystickVector.y = 0;
  31038. this._touches.remove(e.pointerId.toString());
  31039. };
  31040. /**
  31041. * Change the color of the virtual joystick
  31042. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31043. */
  31044. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31045. this._joystickColor = newColor;
  31046. };
  31047. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31048. this._action = action;
  31049. };
  31050. // Define which axis you'd like to control for left & right
  31051. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31052. switch (axis) {
  31053. case JoystickAxis.X:
  31054. case JoystickAxis.Y:
  31055. case JoystickAxis.Z:
  31056. this._axisTargetedByLeftAndRight = axis;
  31057. break;
  31058. default:
  31059. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31060. break;
  31061. }
  31062. };
  31063. // Define which axis you'd like to control for up & down
  31064. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31065. switch (axis) {
  31066. case JoystickAxis.X:
  31067. case JoystickAxis.Y:
  31068. case JoystickAxis.Z:
  31069. this._axisTargetedByUpAndDown = axis;
  31070. break;
  31071. default:
  31072. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31073. break;
  31074. }
  31075. };
  31076. VirtualJoystick.prototype._clearCanvas = function () {
  31077. if (this._leftJoystick) {
  31078. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31079. }
  31080. else {
  31081. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31082. }
  31083. };
  31084. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31085. var _this = this;
  31086. if (this.pressed) {
  31087. this._touches.forEach(function (touch) {
  31088. if (touch.pointerId === _this._joystickPointerID) {
  31089. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31090. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31091. VirtualJoystick.vjCanvasContext.beginPath();
  31092. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31094. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31095. VirtualJoystick.vjCanvasContext.stroke();
  31096. VirtualJoystick.vjCanvasContext.closePath();
  31097. VirtualJoystick.vjCanvasContext.beginPath();
  31098. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31099. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31101. VirtualJoystick.vjCanvasContext.stroke();
  31102. VirtualJoystick.vjCanvasContext.closePath();
  31103. VirtualJoystick.vjCanvasContext.beginPath();
  31104. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31106. VirtualJoystick.vjCanvasContext.stroke();
  31107. VirtualJoystick.vjCanvasContext.closePath();
  31108. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31109. }
  31110. else {
  31111. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31112. VirtualJoystick.vjCanvasContext.beginPath();
  31113. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31114. VirtualJoystick.vjCanvasContext.beginPath();
  31115. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31116. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31117. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31118. VirtualJoystick.vjCanvasContext.stroke();
  31119. VirtualJoystick.vjCanvasContext.closePath();
  31120. touch.prevX = touch.x;
  31121. touch.prevY = touch.y;
  31122. }
  31123. ;
  31124. });
  31125. }
  31126. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31127. };
  31128. VirtualJoystick.prototype.releaseCanvas = function () {
  31129. if (VirtualJoystick.vjCanvas) {
  31130. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31131. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31132. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31133. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31134. window.removeEventListener("resize", this._onResize);
  31135. document.body.removeChild(VirtualJoystick.vjCanvas);
  31136. VirtualJoystick.vjCanvas = null;
  31137. }
  31138. };
  31139. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31140. VirtualJoystick._globalJoystickIndex = 0;
  31141. return VirtualJoystick;
  31142. })();
  31143. BABYLON.VirtualJoystick = VirtualJoystick;
  31144. })(BABYLON || (BABYLON = {}));
  31145. var BABYLON;
  31146. (function (BABYLON) {
  31147. // We're mainly based on the logic defined into the FreeCamera code
  31148. var VirtualJoysticksCamera = (function (_super) {
  31149. __extends(VirtualJoysticksCamera, _super);
  31150. function VirtualJoysticksCamera(name, position, scene) {
  31151. _super.call(this, name, position, scene);
  31152. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31153. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31154. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31155. this._leftjoystick.setJoystickSensibility(0.15);
  31156. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31157. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31158. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31159. this._rightjoystick.reverseUpDown = true;
  31160. this._rightjoystick.setJoystickSensibility(0.05);
  31161. this._rightjoystick.setJoystickColor("yellow");
  31162. }
  31163. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31164. return this._leftjoystick;
  31165. };
  31166. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31167. return this._rightjoystick;
  31168. };
  31169. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31170. var speed = this._computeLocalCameraSpeed() * 50;
  31171. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31172. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31173. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31174. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31175. if (!this._leftjoystick.pressed) {
  31176. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31177. }
  31178. if (!this._rightjoystick.pressed) {
  31179. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31180. }
  31181. _super.prototype._checkInputs.call(this);
  31182. };
  31183. VirtualJoysticksCamera.prototype.dispose = function () {
  31184. this._leftjoystick.releaseCanvas();
  31185. _super.prototype.dispose.call(this);
  31186. };
  31187. return VirtualJoysticksCamera;
  31188. })(BABYLON.FreeCamera);
  31189. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31190. })(BABYLON || (BABYLON = {}));
  31191. var BABYLON;
  31192. (function (BABYLON) {
  31193. var AnaglyphPostProcess = (function (_super) {
  31194. __extends(AnaglyphPostProcess, _super);
  31195. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31196. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31197. }
  31198. return AnaglyphPostProcess;
  31199. })(BABYLON.PostProcess);
  31200. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31201. })(BABYLON || (BABYLON = {}));
  31202. var BABYLON;
  31203. (function (BABYLON) {
  31204. var OutlineRenderer = (function () {
  31205. function OutlineRenderer(scene) {
  31206. this._scene = scene;
  31207. }
  31208. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31209. var _this = this;
  31210. if (useOverlay === void 0) { useOverlay = false; }
  31211. var scene = this._scene;
  31212. var engine = this._scene.getEngine();
  31213. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31214. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31215. return;
  31216. }
  31217. var mesh = subMesh.getRenderingMesh();
  31218. var material = subMesh.getMaterial();
  31219. engine.enableEffect(this._effect);
  31220. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31221. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31222. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31223. // Bones
  31224. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31225. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31226. }
  31227. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31228. // Alpha test
  31229. if (material && material.needAlphaTesting()) {
  31230. var alphaTexture = material.getAlphaTestTexture();
  31231. this._effect.setTexture("diffuseSampler", alphaTexture);
  31232. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31233. }
  31234. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31235. };
  31236. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31237. var defines = [];
  31238. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31239. var mesh = subMesh.getMesh();
  31240. var material = subMesh.getMaterial();
  31241. // Alpha test
  31242. if (material && material.needAlphaTesting()) {
  31243. defines.push("#define ALPHATEST");
  31244. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31245. attribs.push(BABYLON.VertexBuffer.UVKind);
  31246. defines.push("#define UV1");
  31247. }
  31248. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31249. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31250. defines.push("#define UV2");
  31251. }
  31252. }
  31253. // Bones
  31254. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31257. if (mesh.numBoneInfluencers > 4) {
  31258. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31259. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31260. }
  31261. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31262. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31263. }
  31264. else {
  31265. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31266. }
  31267. // Instances
  31268. if (useInstances) {
  31269. defines.push("#define INSTANCES");
  31270. attribs.push("world0");
  31271. attribs.push("world1");
  31272. attribs.push("world2");
  31273. attribs.push("world3");
  31274. }
  31275. // Get correct effect
  31276. var join = defines.join("\n");
  31277. if (this._cachedDefines !== join) {
  31278. this._cachedDefines = join;
  31279. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31280. }
  31281. return this._effect.isReady();
  31282. };
  31283. return OutlineRenderer;
  31284. })();
  31285. BABYLON.OutlineRenderer = OutlineRenderer;
  31286. })(BABYLON || (BABYLON = {}));
  31287. var BABYLON;
  31288. (function (BABYLON) {
  31289. var MeshAssetTask = (function () {
  31290. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31291. this.name = name;
  31292. this.meshesNames = meshesNames;
  31293. this.rootUrl = rootUrl;
  31294. this.sceneFilename = sceneFilename;
  31295. this.isCompleted = false;
  31296. }
  31297. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31298. var _this = this;
  31299. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31300. _this.loadedMeshes = meshes;
  31301. _this.loadedParticleSystems = particleSystems;
  31302. _this.loadedSkeletons = skeletons;
  31303. _this.isCompleted = true;
  31304. if (_this.onSuccess) {
  31305. _this.onSuccess(_this);
  31306. }
  31307. onSuccess();
  31308. }, null, function () {
  31309. if (_this.onError) {
  31310. _this.onError(_this);
  31311. }
  31312. onError();
  31313. });
  31314. };
  31315. return MeshAssetTask;
  31316. })();
  31317. BABYLON.MeshAssetTask = MeshAssetTask;
  31318. var TextFileAssetTask = (function () {
  31319. function TextFileAssetTask(name, url) {
  31320. this.name = name;
  31321. this.url = url;
  31322. this.isCompleted = false;
  31323. }
  31324. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31325. var _this = this;
  31326. BABYLON.Tools.LoadFile(this.url, function (data) {
  31327. _this.text = data;
  31328. _this.isCompleted = true;
  31329. if (_this.onSuccess) {
  31330. _this.onSuccess(_this);
  31331. }
  31332. onSuccess();
  31333. }, null, scene.database, false, function () {
  31334. if (_this.onError) {
  31335. _this.onError(_this);
  31336. }
  31337. onError();
  31338. });
  31339. };
  31340. return TextFileAssetTask;
  31341. })();
  31342. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31343. var BinaryFileAssetTask = (function () {
  31344. function BinaryFileAssetTask(name, url) {
  31345. this.name = name;
  31346. this.url = url;
  31347. this.isCompleted = false;
  31348. }
  31349. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31350. var _this = this;
  31351. BABYLON.Tools.LoadFile(this.url, function (data) {
  31352. _this.data = data;
  31353. _this.isCompleted = true;
  31354. if (_this.onSuccess) {
  31355. _this.onSuccess(_this);
  31356. }
  31357. onSuccess();
  31358. }, null, scene.database, true, function () {
  31359. if (_this.onError) {
  31360. _this.onError(_this);
  31361. }
  31362. onError();
  31363. });
  31364. };
  31365. return BinaryFileAssetTask;
  31366. })();
  31367. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31368. var ImageAssetTask = (function () {
  31369. function ImageAssetTask(name, url) {
  31370. this.name = name;
  31371. this.url = url;
  31372. this.isCompleted = false;
  31373. }
  31374. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31375. var _this = this;
  31376. var img = new Image();
  31377. img.onload = function () {
  31378. _this.image = img;
  31379. _this.isCompleted = true;
  31380. if (_this.onSuccess) {
  31381. _this.onSuccess(_this);
  31382. }
  31383. onSuccess();
  31384. };
  31385. img.onerror = function () {
  31386. if (_this.onError) {
  31387. _this.onError(_this);
  31388. }
  31389. onError();
  31390. };
  31391. img.src = this.url;
  31392. };
  31393. return ImageAssetTask;
  31394. })();
  31395. BABYLON.ImageAssetTask = ImageAssetTask;
  31396. var TextureAssetTask = (function () {
  31397. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31399. this.name = name;
  31400. this.url = url;
  31401. this.noMipmap = noMipmap;
  31402. this.invertY = invertY;
  31403. this.samplingMode = samplingMode;
  31404. this.isCompleted = false;
  31405. }
  31406. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31407. var _this = this;
  31408. var onload = function () {
  31409. _this.isCompleted = true;
  31410. if (_this.onSuccess) {
  31411. _this.onSuccess(_this);
  31412. }
  31413. onSuccess();
  31414. };
  31415. var onerror = function () {
  31416. if (_this.onError) {
  31417. _this.onError(_this);
  31418. }
  31419. onError();
  31420. };
  31421. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31422. };
  31423. return TextureAssetTask;
  31424. })();
  31425. BABYLON.TextureAssetTask = TextureAssetTask;
  31426. var AssetsManager = (function () {
  31427. function AssetsManager(scene) {
  31428. this._tasks = new Array();
  31429. this._waitingTasksCount = 0;
  31430. this.useDefaultLoadingScreen = true;
  31431. this._scene = scene;
  31432. }
  31433. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31434. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31435. this._tasks.push(task);
  31436. return task;
  31437. };
  31438. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31439. var task = new TextFileAssetTask(taskName, url);
  31440. this._tasks.push(task);
  31441. return task;
  31442. };
  31443. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31444. var task = new BinaryFileAssetTask(taskName, url);
  31445. this._tasks.push(task);
  31446. return task;
  31447. };
  31448. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31449. var task = new ImageAssetTask(taskName, url);
  31450. this._tasks.push(task);
  31451. return task;
  31452. };
  31453. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31455. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31456. this._tasks.push(task);
  31457. return task;
  31458. };
  31459. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31460. this._waitingTasksCount--;
  31461. if (this._waitingTasksCount === 0) {
  31462. if (this.onFinish) {
  31463. this.onFinish(this._tasks);
  31464. }
  31465. this._scene.getEngine().hideLoadingUI();
  31466. }
  31467. };
  31468. AssetsManager.prototype._runTask = function (task) {
  31469. var _this = this;
  31470. task.run(this._scene, function () {
  31471. if (_this.onTaskSuccess) {
  31472. _this.onTaskSuccess(task);
  31473. }
  31474. _this._decreaseWaitingTasksCount();
  31475. }, function () {
  31476. if (_this.onTaskError) {
  31477. _this.onTaskError(task);
  31478. }
  31479. _this._decreaseWaitingTasksCount();
  31480. });
  31481. };
  31482. AssetsManager.prototype.reset = function () {
  31483. this._tasks = new Array();
  31484. return this;
  31485. };
  31486. AssetsManager.prototype.load = function () {
  31487. this._waitingTasksCount = this._tasks.length;
  31488. if (this._waitingTasksCount === 0) {
  31489. if (this.onFinish) {
  31490. this.onFinish(this._tasks);
  31491. }
  31492. return this;
  31493. }
  31494. if (this.useDefaultLoadingScreen) {
  31495. this._scene.getEngine().displayLoadingUI();
  31496. }
  31497. for (var index = 0; index < this._tasks.length; index++) {
  31498. var task = this._tasks[index];
  31499. this._runTask(task);
  31500. }
  31501. return this;
  31502. };
  31503. return AssetsManager;
  31504. })();
  31505. BABYLON.AssetsManager = AssetsManager;
  31506. })(BABYLON || (BABYLON = {}));
  31507. var BABYLON;
  31508. (function (BABYLON) {
  31509. var VRDeviceOrientationFreeCamera = (function (_super) {
  31510. __extends(VRDeviceOrientationFreeCamera, _super);
  31511. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31512. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31513. _super.call(this, name, position, scene);
  31514. this._alpha = 0;
  31515. this._beta = 0;
  31516. this._gamma = 0;
  31517. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31518. metrics.compensateDistortion = compensateDistortion;
  31519. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31520. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31521. }
  31522. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31523. this._alpha = +evt.alpha | 0;
  31524. this._beta = +evt.beta | 0;
  31525. this._gamma = +evt.gamma | 0;
  31526. if (this._gamma < 0) {
  31527. this._gamma = 90 + this._gamma;
  31528. }
  31529. else {
  31530. // Incline it in the correct angle.
  31531. this._gamma = 270 - this._gamma;
  31532. }
  31533. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31534. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31535. this.rotation.z = this._beta / 180.0 * Math.PI;
  31536. };
  31537. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31538. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31539. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31540. };
  31541. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31542. _super.prototype.detachControl.call(this, element);
  31543. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31544. };
  31545. return VRDeviceOrientationFreeCamera;
  31546. })(BABYLON.FreeCamera);
  31547. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31548. })(BABYLON || (BABYLON = {}));
  31549. var BABYLON;
  31550. (function (BABYLON) {
  31551. var WebVRFreeCamera = (function (_super) {
  31552. __extends(WebVRFreeCamera, _super);
  31553. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31554. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31555. _super.call(this, name, position, scene);
  31556. this._hmdDevice = null;
  31557. this._sensorDevice = null;
  31558. this._cacheState = null;
  31559. this._cacheQuaternion = new BABYLON.Quaternion();
  31560. this._cacheRotation = BABYLON.Vector3.Zero();
  31561. this._vrEnabled = false;
  31562. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31563. metrics.compensateDistortion = compensateDistortion;
  31564. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31565. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31566. }
  31567. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31568. var size = devices.length;
  31569. var i = 0;
  31570. // Reset devices.
  31571. this._sensorDevice = null;
  31572. this._hmdDevice = null;
  31573. // Search for a HmdDevice.
  31574. while (i < size && this._hmdDevice === null) {
  31575. if (devices[i] instanceof HMDVRDevice) {
  31576. this._hmdDevice = devices[i];
  31577. }
  31578. i++;
  31579. }
  31580. i = 0;
  31581. while (i < size && this._sensorDevice === null) {
  31582. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31583. this._sensorDevice = devices[i];
  31584. }
  31585. i++;
  31586. }
  31587. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31588. };
  31589. WebVRFreeCamera.prototype._checkInputs = function () {
  31590. if (this._vrEnabled) {
  31591. this._cacheState = this._sensorDevice.getState();
  31592. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31593. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31594. this.rotation.x = -this._cacheRotation.z;
  31595. this.rotation.y = -this._cacheRotation.y;
  31596. this.rotation.z = this._cacheRotation.x;
  31597. }
  31598. _super.prototype._checkInputs.call(this);
  31599. };
  31600. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31601. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31602. if (navigator.getVRDevices) {
  31603. navigator.getVRDevices().then(this._getWebVRDevices);
  31604. }
  31605. else if (navigator.mozGetVRDevices) {
  31606. navigator.mozGetVRDevices(this._getWebVRDevices);
  31607. }
  31608. };
  31609. WebVRFreeCamera.prototype.detachControl = function (element) {
  31610. _super.prototype.detachControl.call(this, element);
  31611. this._vrEnabled = false;
  31612. };
  31613. return WebVRFreeCamera;
  31614. })(BABYLON.FreeCamera);
  31615. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31616. })(BABYLON || (BABYLON = {}));
  31617. var BABYLON;
  31618. (function (BABYLON) {
  31619. // Standard optimizations
  31620. var SceneOptimization = (function () {
  31621. function SceneOptimization(priority) {
  31622. if (priority === void 0) { priority = 0; }
  31623. this.priority = priority;
  31624. this.apply = function (scene) {
  31625. return true; // Return true if everything that can be done was applied
  31626. };
  31627. }
  31628. return SceneOptimization;
  31629. })();
  31630. BABYLON.SceneOptimization = SceneOptimization;
  31631. var TextureOptimization = (function (_super) {
  31632. __extends(TextureOptimization, _super);
  31633. function TextureOptimization(priority, maximumSize) {
  31634. var _this = this;
  31635. if (priority === void 0) { priority = 0; }
  31636. if (maximumSize === void 0) { maximumSize = 1024; }
  31637. _super.call(this, priority);
  31638. this.priority = priority;
  31639. this.maximumSize = maximumSize;
  31640. this.apply = function (scene) {
  31641. var allDone = true;
  31642. for (var index = 0; index < scene.textures.length; index++) {
  31643. var texture = scene.textures[index];
  31644. if (!texture.canRescale) {
  31645. continue;
  31646. }
  31647. var currentSize = texture.getSize();
  31648. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31649. if (maxDimension > _this.maximumSize) {
  31650. texture.scale(0.5);
  31651. allDone = false;
  31652. }
  31653. }
  31654. return allDone;
  31655. };
  31656. }
  31657. return TextureOptimization;
  31658. })(SceneOptimization);
  31659. BABYLON.TextureOptimization = TextureOptimization;
  31660. var HardwareScalingOptimization = (function (_super) {
  31661. __extends(HardwareScalingOptimization, _super);
  31662. function HardwareScalingOptimization(priority, maximumScale) {
  31663. var _this = this;
  31664. if (priority === void 0) { priority = 0; }
  31665. if (maximumScale === void 0) { maximumScale = 2; }
  31666. _super.call(this, priority);
  31667. this.priority = priority;
  31668. this.maximumScale = maximumScale;
  31669. this._currentScale = 1;
  31670. this.apply = function (scene) {
  31671. _this._currentScale++;
  31672. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31673. return _this._currentScale >= _this.maximumScale;
  31674. };
  31675. }
  31676. return HardwareScalingOptimization;
  31677. })(SceneOptimization);
  31678. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31679. var ShadowsOptimization = (function (_super) {
  31680. __extends(ShadowsOptimization, _super);
  31681. function ShadowsOptimization() {
  31682. _super.apply(this, arguments);
  31683. this.apply = function (scene) {
  31684. scene.shadowsEnabled = false;
  31685. return true;
  31686. };
  31687. }
  31688. return ShadowsOptimization;
  31689. })(SceneOptimization);
  31690. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31691. var PostProcessesOptimization = (function (_super) {
  31692. __extends(PostProcessesOptimization, _super);
  31693. function PostProcessesOptimization() {
  31694. _super.apply(this, arguments);
  31695. this.apply = function (scene) {
  31696. scene.postProcessesEnabled = false;
  31697. return true;
  31698. };
  31699. }
  31700. return PostProcessesOptimization;
  31701. })(SceneOptimization);
  31702. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31703. var LensFlaresOptimization = (function (_super) {
  31704. __extends(LensFlaresOptimization, _super);
  31705. function LensFlaresOptimization() {
  31706. _super.apply(this, arguments);
  31707. this.apply = function (scene) {
  31708. scene.lensFlaresEnabled = false;
  31709. return true;
  31710. };
  31711. }
  31712. return LensFlaresOptimization;
  31713. })(SceneOptimization);
  31714. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31715. var ParticlesOptimization = (function (_super) {
  31716. __extends(ParticlesOptimization, _super);
  31717. function ParticlesOptimization() {
  31718. _super.apply(this, arguments);
  31719. this.apply = function (scene) {
  31720. scene.particlesEnabled = false;
  31721. return true;
  31722. };
  31723. }
  31724. return ParticlesOptimization;
  31725. })(SceneOptimization);
  31726. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31727. var RenderTargetsOptimization = (function (_super) {
  31728. __extends(RenderTargetsOptimization, _super);
  31729. function RenderTargetsOptimization() {
  31730. _super.apply(this, arguments);
  31731. this.apply = function (scene) {
  31732. scene.renderTargetsEnabled = false;
  31733. return true;
  31734. };
  31735. }
  31736. return RenderTargetsOptimization;
  31737. })(SceneOptimization);
  31738. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31739. var MergeMeshesOptimization = (function (_super) {
  31740. __extends(MergeMeshesOptimization, _super);
  31741. function MergeMeshesOptimization() {
  31742. var _this = this;
  31743. _super.apply(this, arguments);
  31744. this._canBeMerged = function (abstractMesh) {
  31745. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31746. return false;
  31747. }
  31748. var mesh = abstractMesh;
  31749. if (!mesh.isVisible || !mesh.isEnabled()) {
  31750. return false;
  31751. }
  31752. if (mesh.instances.length > 0) {
  31753. return false;
  31754. }
  31755. if (mesh.skeleton || mesh.hasLODLevels) {
  31756. return false;
  31757. }
  31758. if (mesh.parent) {
  31759. return false;
  31760. }
  31761. return true;
  31762. };
  31763. this.apply = function (scene, updateSelectionTree) {
  31764. var globalPool = scene.meshes.slice(0);
  31765. var globalLength = globalPool.length;
  31766. for (var index = 0; index < globalLength; index++) {
  31767. var currentPool = new Array();
  31768. var current = globalPool[index];
  31769. // Checks
  31770. if (!_this._canBeMerged(current)) {
  31771. continue;
  31772. }
  31773. currentPool.push(current);
  31774. // Find compatible meshes
  31775. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31776. var otherMesh = globalPool[subIndex];
  31777. if (!_this._canBeMerged(otherMesh)) {
  31778. continue;
  31779. }
  31780. if (otherMesh.material !== current.material) {
  31781. continue;
  31782. }
  31783. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31784. continue;
  31785. }
  31786. currentPool.push(otherMesh);
  31787. globalLength--;
  31788. globalPool.splice(subIndex, 1);
  31789. subIndex--;
  31790. }
  31791. if (currentPool.length < 2) {
  31792. continue;
  31793. }
  31794. // Merge meshes
  31795. BABYLON.Mesh.MergeMeshes(currentPool);
  31796. }
  31797. if (updateSelectionTree != undefined) {
  31798. if (updateSelectionTree) {
  31799. scene.createOrUpdateSelectionOctree();
  31800. }
  31801. }
  31802. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31803. scene.createOrUpdateSelectionOctree();
  31804. }
  31805. return true;
  31806. };
  31807. }
  31808. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31809. get: function () {
  31810. return MergeMeshesOptimization._UpdateSelectionTree;
  31811. },
  31812. set: function (value) {
  31813. MergeMeshesOptimization._UpdateSelectionTree = value;
  31814. },
  31815. enumerable: true,
  31816. configurable: true
  31817. });
  31818. MergeMeshesOptimization._UpdateSelectionTree = false;
  31819. return MergeMeshesOptimization;
  31820. })(SceneOptimization);
  31821. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31822. // Options
  31823. var SceneOptimizerOptions = (function () {
  31824. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31825. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31826. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31827. this.targetFrameRate = targetFrameRate;
  31828. this.trackerDuration = trackerDuration;
  31829. this.optimizations = new Array();
  31830. }
  31831. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31832. var result = new SceneOptimizerOptions(targetFrameRate);
  31833. var priority = 0;
  31834. result.optimizations.push(new MergeMeshesOptimization(priority));
  31835. result.optimizations.push(new ShadowsOptimization(priority));
  31836. result.optimizations.push(new LensFlaresOptimization(priority));
  31837. // Next priority
  31838. priority++;
  31839. result.optimizations.push(new PostProcessesOptimization(priority));
  31840. result.optimizations.push(new ParticlesOptimization(priority));
  31841. // Next priority
  31842. priority++;
  31843. result.optimizations.push(new TextureOptimization(priority, 1024));
  31844. return result;
  31845. };
  31846. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31847. var result = new SceneOptimizerOptions(targetFrameRate);
  31848. var priority = 0;
  31849. result.optimizations.push(new MergeMeshesOptimization(priority));
  31850. result.optimizations.push(new ShadowsOptimization(priority));
  31851. result.optimizations.push(new LensFlaresOptimization(priority));
  31852. // Next priority
  31853. priority++;
  31854. result.optimizations.push(new PostProcessesOptimization(priority));
  31855. result.optimizations.push(new ParticlesOptimization(priority));
  31856. // Next priority
  31857. priority++;
  31858. result.optimizations.push(new TextureOptimization(priority, 512));
  31859. // Next priority
  31860. priority++;
  31861. result.optimizations.push(new RenderTargetsOptimization(priority));
  31862. // Next priority
  31863. priority++;
  31864. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31865. return result;
  31866. };
  31867. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31868. var result = new SceneOptimizerOptions(targetFrameRate);
  31869. var priority = 0;
  31870. result.optimizations.push(new MergeMeshesOptimization(priority));
  31871. result.optimizations.push(new ShadowsOptimization(priority));
  31872. result.optimizations.push(new LensFlaresOptimization(priority));
  31873. // Next priority
  31874. priority++;
  31875. result.optimizations.push(new PostProcessesOptimization(priority));
  31876. result.optimizations.push(new ParticlesOptimization(priority));
  31877. // Next priority
  31878. priority++;
  31879. result.optimizations.push(new TextureOptimization(priority, 256));
  31880. // Next priority
  31881. priority++;
  31882. result.optimizations.push(new RenderTargetsOptimization(priority));
  31883. // Next priority
  31884. priority++;
  31885. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31886. return result;
  31887. };
  31888. return SceneOptimizerOptions;
  31889. })();
  31890. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31891. // Scene optimizer tool
  31892. var SceneOptimizer = (function () {
  31893. function SceneOptimizer() {
  31894. }
  31895. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31896. // TODO: add an epsilon
  31897. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31898. if (onSuccess) {
  31899. onSuccess();
  31900. }
  31901. return;
  31902. }
  31903. // Apply current level of optimizations
  31904. var allDone = true;
  31905. var noOptimizationApplied = true;
  31906. for (var index = 0; index < options.optimizations.length; index++) {
  31907. var optimization = options.optimizations[index];
  31908. if (optimization.priority === currentPriorityLevel) {
  31909. noOptimizationApplied = false;
  31910. allDone = allDone && optimization.apply(scene);
  31911. }
  31912. }
  31913. // If no optimization was applied, this is a failure :(
  31914. if (noOptimizationApplied) {
  31915. if (onFailure) {
  31916. onFailure();
  31917. }
  31918. return;
  31919. }
  31920. // If all optimizations were done, move to next level
  31921. if (allDone) {
  31922. currentPriorityLevel++;
  31923. }
  31924. // Let's the system running for a specific amount of time before checking FPS
  31925. scene.executeWhenReady(function () {
  31926. setTimeout(function () {
  31927. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31928. }, options.trackerDuration);
  31929. });
  31930. };
  31931. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31932. if (!options) {
  31933. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31934. }
  31935. // Let's the system running for a specific amount of time before checking FPS
  31936. scene.executeWhenReady(function () {
  31937. setTimeout(function () {
  31938. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31939. }, options.trackerDuration);
  31940. });
  31941. };
  31942. return SceneOptimizer;
  31943. })();
  31944. BABYLON.SceneOptimizer = SceneOptimizer;
  31945. })(BABYLON || (BABYLON = {}));
  31946. var BABYLON;
  31947. (function (BABYLON) {
  31948. var Internals;
  31949. (function (Internals) {
  31950. var MeshLODLevel = (function () {
  31951. function MeshLODLevel(distance, mesh) {
  31952. this.distance = distance;
  31953. this.mesh = mesh;
  31954. }
  31955. return MeshLODLevel;
  31956. })();
  31957. Internals.MeshLODLevel = MeshLODLevel;
  31958. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31959. })(BABYLON || (BABYLON = {}));
  31960. var BABYLON;
  31961. (function (BABYLON) {
  31962. var RawTexture = (function (_super) {
  31963. __extends(RawTexture, _super);
  31964. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31966. if (invertY === void 0) { invertY = false; }
  31967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31968. _super.call(this, null, scene, !generateMipMaps, invertY);
  31969. this.format = format;
  31970. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31971. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31972. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31973. }
  31974. RawTexture.prototype.update = function (data) {
  31975. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31976. };
  31977. // Statics
  31978. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31980. if (invertY === void 0) { invertY = false; }
  31981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31982. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31983. };
  31984. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31986. if (invertY === void 0) { invertY = false; }
  31987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31988. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31989. };
  31990. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31992. if (invertY === void 0) { invertY = false; }
  31993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31994. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31995. };
  31996. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31997. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31998. if (invertY === void 0) { invertY = false; }
  31999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32001. };
  32002. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32004. if (invertY === void 0) { invertY = false; }
  32005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32006. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32007. };
  32008. return RawTexture;
  32009. })(BABYLON.Texture);
  32010. BABYLON.RawTexture = RawTexture;
  32011. })(BABYLON || (BABYLON = {}));
  32012. var BABYLON;
  32013. (function (BABYLON) {
  32014. var IndexedVector2 = (function (_super) {
  32015. __extends(IndexedVector2, _super);
  32016. function IndexedVector2(original, index) {
  32017. _super.call(this, original.x, original.y);
  32018. this.index = index;
  32019. }
  32020. return IndexedVector2;
  32021. })(BABYLON.Vector2);
  32022. var PolygonPoints = (function () {
  32023. function PolygonPoints() {
  32024. this.elements = new Array();
  32025. }
  32026. PolygonPoints.prototype.add = function (originalPoints) {
  32027. var _this = this;
  32028. var result = new Array();
  32029. originalPoints.forEach(function (point) {
  32030. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32031. var newPoint = new IndexedVector2(point, _this.elements.length);
  32032. result.push(newPoint);
  32033. _this.elements.push(newPoint);
  32034. }
  32035. });
  32036. return result;
  32037. };
  32038. PolygonPoints.prototype.computeBounds = function () {
  32039. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32040. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32041. this.elements.forEach(function (point) {
  32042. // x
  32043. if (point.x < lmin.x) {
  32044. lmin.x = point.x;
  32045. }
  32046. else if (point.x > lmax.x) {
  32047. lmax.x = point.x;
  32048. }
  32049. // y
  32050. if (point.y < lmin.y) {
  32051. lmin.y = point.y;
  32052. }
  32053. else if (point.y > lmax.y) {
  32054. lmax.y = point.y;
  32055. }
  32056. });
  32057. return {
  32058. min: lmin,
  32059. max: lmax,
  32060. width: lmax.x - lmin.x,
  32061. height: lmax.y - lmin.y
  32062. };
  32063. };
  32064. return PolygonPoints;
  32065. })();
  32066. var Polygon = (function () {
  32067. function Polygon() {
  32068. }
  32069. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32070. return [
  32071. new BABYLON.Vector2(xmin, ymin),
  32072. new BABYLON.Vector2(xmax, ymin),
  32073. new BABYLON.Vector2(xmax, ymax),
  32074. new BABYLON.Vector2(xmin, ymax)
  32075. ];
  32076. };
  32077. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32078. if (cx === void 0) { cx = 0; }
  32079. if (cy === void 0) { cy = 0; }
  32080. if (numberOfSides === void 0) { numberOfSides = 32; }
  32081. var result = new Array();
  32082. var angle = 0;
  32083. var increment = (Math.PI * 2) / numberOfSides;
  32084. for (var i = 0; i < numberOfSides; i++) {
  32085. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32086. angle -= increment;
  32087. }
  32088. return result;
  32089. };
  32090. Polygon.Parse = function (input) {
  32091. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32092. var i, result = [];
  32093. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32094. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32095. }
  32096. return result;
  32097. };
  32098. Polygon.StartingAt = function (x, y) {
  32099. return BABYLON.Path2.StartingAt(x, y);
  32100. };
  32101. return Polygon;
  32102. })();
  32103. BABYLON.Polygon = Polygon;
  32104. var PolygonMeshBuilder = (function () {
  32105. function PolygonMeshBuilder(name, contours, scene) {
  32106. this._points = new PolygonPoints();
  32107. this._outlinepoints = new PolygonPoints();
  32108. this._holes = [];
  32109. if (!("poly2tri" in window)) {
  32110. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32111. }
  32112. this._name = name;
  32113. this._scene = scene;
  32114. var points;
  32115. if (contours instanceof BABYLON.Path2) {
  32116. points = contours.getPoints();
  32117. }
  32118. else {
  32119. points = contours;
  32120. }
  32121. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32122. this._outlinepoints.add(points);
  32123. }
  32124. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32125. this._swctx.addHole(this._points.add(hole));
  32126. var holepoints = new PolygonPoints();
  32127. holepoints.add(hole);
  32128. this._holes.push(holepoints);
  32129. return this;
  32130. };
  32131. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32132. var _this = this;
  32133. if (updatable === void 0) { updatable = false; }
  32134. var result = new BABYLON.Mesh(this._name, this._scene);
  32135. var normals = [];
  32136. var positions = [];
  32137. var uvs = [];
  32138. var bounds = this._points.computeBounds();
  32139. this._points.elements.forEach(function (p) {
  32140. normals.push(0, 1.0, 0);
  32141. positions.push(p.x, 0, p.y);
  32142. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32143. });
  32144. var indices = [];
  32145. this._swctx.triangulate();
  32146. this._swctx.getTriangles().forEach(function (triangle) {
  32147. triangle.getPoints().forEach(function (point) {
  32148. indices.push(point.index);
  32149. });
  32150. });
  32151. if (depth > 0) {
  32152. var positionscount = (positions.length / 3); //get the current pointcount
  32153. this._points.elements.forEach(function (p) {
  32154. normals.push(0, -1.0, 0);
  32155. positions.push(p.x, -depth, p.y);
  32156. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32157. });
  32158. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32159. var p2;
  32160. var poscounter = 0;
  32161. this._swctx.getTriangles().forEach(function (triangle) {
  32162. triangle.getPoints().forEach(function (point) {
  32163. switch (poscounter) {
  32164. case 0:
  32165. p1 = point;
  32166. break;
  32167. case 1:
  32168. p2 = point;
  32169. break;
  32170. case 2:
  32171. indices.push(point.index + positionscount);
  32172. indices.push(p2.index + positionscount);
  32173. indices.push(p1.index + positionscount);
  32174. poscounter = -1;
  32175. break;
  32176. }
  32177. poscounter++;
  32178. //indices.push((<IndexedVector2>point).index + positionscount);
  32179. });
  32180. });
  32181. //Add the sides
  32182. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32183. this._holes.forEach(function (hole) {
  32184. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32185. });
  32186. }
  32187. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32188. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32189. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32190. result.setIndices(indices);
  32191. return result;
  32192. };
  32193. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32194. var StartIndex = positions.length / 3;
  32195. var ulength = 0;
  32196. for (var i = 0; i < points.elements.length; i++) {
  32197. var p = points.elements[i];
  32198. var p1;
  32199. if ((i + 1) > points.elements.length - 1) {
  32200. p1 = points.elements[0];
  32201. }
  32202. else {
  32203. p1 = points.elements[i + 1];
  32204. }
  32205. positions.push(p.x, 0, p.y);
  32206. positions.push(p.x, -depth, p.y);
  32207. positions.push(p1.x, 0, p1.y);
  32208. positions.push(p1.x, -depth, p1.y);
  32209. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32210. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32211. var v3 = v2.subtract(v1);
  32212. var v4 = new BABYLON.Vector3(0, 1, 0);
  32213. var vn = BABYLON.Vector3.Cross(v3, v4);
  32214. vn = vn.normalize();
  32215. uvs.push(ulength / bounds.width, 0);
  32216. uvs.push(ulength / bounds.width, 1);
  32217. ulength += v3.length();
  32218. uvs.push((ulength / bounds.width), 0);
  32219. uvs.push((ulength / bounds.width), 1);
  32220. if (!flip) {
  32221. normals.push(-vn.x, -vn.y, -vn.z);
  32222. normals.push(-vn.x, -vn.y, -vn.z);
  32223. normals.push(-vn.x, -vn.y, -vn.z);
  32224. normals.push(-vn.x, -vn.y, -vn.z);
  32225. indices.push(StartIndex);
  32226. indices.push(StartIndex + 1);
  32227. indices.push(StartIndex + 2);
  32228. indices.push(StartIndex + 1);
  32229. indices.push(StartIndex + 3);
  32230. indices.push(StartIndex + 2);
  32231. }
  32232. else {
  32233. normals.push(vn.x, vn.y, vn.z);
  32234. normals.push(vn.x, vn.y, vn.z);
  32235. normals.push(vn.x, vn.y, vn.z);
  32236. normals.push(vn.x, vn.y, vn.z);
  32237. indices.push(StartIndex);
  32238. indices.push(StartIndex + 2);
  32239. indices.push(StartIndex + 1);
  32240. indices.push(StartIndex + 1);
  32241. indices.push(StartIndex + 2);
  32242. indices.push(StartIndex + 3);
  32243. }
  32244. StartIndex += 4;
  32245. }
  32246. ;
  32247. };
  32248. return PolygonMeshBuilder;
  32249. })();
  32250. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32251. })(BABYLON || (BABYLON = {}));
  32252. var BABYLON;
  32253. (function (BABYLON) {
  32254. var Octree = (function () {
  32255. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32256. if (maxDepth === void 0) { maxDepth = 2; }
  32257. this.maxDepth = maxDepth;
  32258. this.dynamicContent = new Array();
  32259. this._maxBlockCapacity = maxBlockCapacity || 64;
  32260. this._selectionContent = new BABYLON.SmartArray(1024);
  32261. this._creationFunc = creationFunc;
  32262. }
  32263. // Methods
  32264. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32265. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32266. };
  32267. Octree.prototype.addMesh = function (entry) {
  32268. for (var index = 0; index < this.blocks.length; index++) {
  32269. var block = this.blocks[index];
  32270. block.addEntry(entry);
  32271. }
  32272. };
  32273. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32274. this._selectionContent.reset();
  32275. for (var index = 0; index < this.blocks.length; index++) {
  32276. var block = this.blocks[index];
  32277. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32278. }
  32279. if (allowDuplicate) {
  32280. this._selectionContent.concat(this.dynamicContent);
  32281. }
  32282. else {
  32283. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32284. }
  32285. return this._selectionContent;
  32286. };
  32287. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32288. this._selectionContent.reset();
  32289. for (var index = 0; index < this.blocks.length; index++) {
  32290. var block = this.blocks[index];
  32291. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32292. }
  32293. if (allowDuplicate) {
  32294. this._selectionContent.concat(this.dynamicContent);
  32295. }
  32296. else {
  32297. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32298. }
  32299. return this._selectionContent;
  32300. };
  32301. Octree.prototype.intersectsRay = function (ray) {
  32302. this._selectionContent.reset();
  32303. for (var index = 0; index < this.blocks.length; index++) {
  32304. var block = this.blocks[index];
  32305. block.intersectsRay(ray, this._selectionContent);
  32306. }
  32307. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32308. return this._selectionContent;
  32309. };
  32310. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32311. target.blocks = new Array();
  32312. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32313. // Segmenting space
  32314. for (var x = 0; x < 2; x++) {
  32315. for (var y = 0; y < 2; y++) {
  32316. for (var z = 0; z < 2; z++) {
  32317. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32318. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32319. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32320. block.addEntries(entries);
  32321. target.blocks.push(block);
  32322. }
  32323. }
  32324. }
  32325. };
  32326. Octree.CreationFuncForMeshes = function (entry, block) {
  32327. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32328. block.entries.push(entry);
  32329. }
  32330. };
  32331. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32332. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32333. block.entries.push(entry);
  32334. }
  32335. };
  32336. return Octree;
  32337. })();
  32338. BABYLON.Octree = Octree;
  32339. })(BABYLON || (BABYLON = {}));
  32340. var BABYLON;
  32341. (function (BABYLON) {
  32342. var OctreeBlock = (function () {
  32343. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32344. this.entries = new Array();
  32345. this._boundingVectors = new Array();
  32346. this._capacity = capacity;
  32347. this._depth = depth;
  32348. this._maxDepth = maxDepth;
  32349. this._creationFunc = creationFunc;
  32350. this._minPoint = minPoint;
  32351. this._maxPoint = maxPoint;
  32352. this._boundingVectors.push(minPoint.clone());
  32353. this._boundingVectors.push(maxPoint.clone());
  32354. this._boundingVectors.push(minPoint.clone());
  32355. this._boundingVectors[2].x = maxPoint.x;
  32356. this._boundingVectors.push(minPoint.clone());
  32357. this._boundingVectors[3].y = maxPoint.y;
  32358. this._boundingVectors.push(minPoint.clone());
  32359. this._boundingVectors[4].z = maxPoint.z;
  32360. this._boundingVectors.push(maxPoint.clone());
  32361. this._boundingVectors[5].z = minPoint.z;
  32362. this._boundingVectors.push(maxPoint.clone());
  32363. this._boundingVectors[6].x = minPoint.x;
  32364. this._boundingVectors.push(maxPoint.clone());
  32365. this._boundingVectors[7].y = minPoint.y;
  32366. }
  32367. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32368. // Property
  32369. get: function () {
  32370. return this._capacity;
  32371. },
  32372. enumerable: true,
  32373. configurable: true
  32374. });
  32375. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32376. get: function () {
  32377. return this._minPoint;
  32378. },
  32379. enumerable: true,
  32380. configurable: true
  32381. });
  32382. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32383. get: function () {
  32384. return this._maxPoint;
  32385. },
  32386. enumerable: true,
  32387. configurable: true
  32388. });
  32389. // Methods
  32390. OctreeBlock.prototype.addEntry = function (entry) {
  32391. if (this.blocks) {
  32392. for (var index = 0; index < this.blocks.length; index++) {
  32393. var block = this.blocks[index];
  32394. block.addEntry(entry);
  32395. }
  32396. return;
  32397. }
  32398. this._creationFunc(entry, this);
  32399. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32400. this.createInnerBlocks();
  32401. }
  32402. };
  32403. OctreeBlock.prototype.addEntries = function (entries) {
  32404. for (var index = 0; index < entries.length; index++) {
  32405. var mesh = entries[index];
  32406. this.addEntry(mesh);
  32407. }
  32408. };
  32409. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32410. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32411. if (this.blocks) {
  32412. for (var index = 0; index < this.blocks.length; index++) {
  32413. var block = this.blocks[index];
  32414. block.select(frustumPlanes, selection, allowDuplicate);
  32415. }
  32416. return;
  32417. }
  32418. if (allowDuplicate) {
  32419. selection.concat(this.entries);
  32420. }
  32421. else {
  32422. selection.concatWithNoDuplicate(this.entries);
  32423. }
  32424. }
  32425. };
  32426. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32427. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32428. if (this.blocks) {
  32429. for (var index = 0; index < this.blocks.length; index++) {
  32430. var block = this.blocks[index];
  32431. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32432. }
  32433. return;
  32434. }
  32435. if (allowDuplicate) {
  32436. selection.concat(this.entries);
  32437. }
  32438. else {
  32439. selection.concatWithNoDuplicate(this.entries);
  32440. }
  32441. }
  32442. };
  32443. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32444. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32445. if (this.blocks) {
  32446. for (var index = 0; index < this.blocks.length; index++) {
  32447. var block = this.blocks[index];
  32448. block.intersectsRay(ray, selection);
  32449. }
  32450. return;
  32451. }
  32452. selection.concatWithNoDuplicate(this.entries);
  32453. }
  32454. };
  32455. OctreeBlock.prototype.createInnerBlocks = function () {
  32456. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32457. };
  32458. return OctreeBlock;
  32459. })();
  32460. BABYLON.OctreeBlock = OctreeBlock;
  32461. })(BABYLON || (BABYLON = {}));
  32462. var BABYLON;
  32463. (function (BABYLON) {
  32464. var BlurPostProcess = (function (_super) {
  32465. __extends(BlurPostProcess, _super);
  32466. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32467. var _this = this;
  32468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32469. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32470. this.direction = direction;
  32471. this.blurWidth = blurWidth;
  32472. this.onApply = function (effect) {
  32473. effect.setFloat2("screenSize", _this.width, _this.height);
  32474. effect.setVector2("direction", _this.direction);
  32475. effect.setFloat("blurWidth", _this.blurWidth);
  32476. };
  32477. }
  32478. return BlurPostProcess;
  32479. })(BABYLON.PostProcess);
  32480. BABYLON.BlurPostProcess = BlurPostProcess;
  32481. })(BABYLON || (BABYLON = {}));
  32482. var BABYLON;
  32483. (function (BABYLON) {
  32484. var RefractionPostProcess = (function (_super) {
  32485. __extends(RefractionPostProcess, _super);
  32486. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32487. var _this = this;
  32488. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32489. this.color = color;
  32490. this.depth = depth;
  32491. this.colorLevel = colorLevel;
  32492. this.onActivate = function (cam) {
  32493. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32494. };
  32495. this.onApply = function (effect) {
  32496. effect.setColor3("baseColor", _this.color);
  32497. effect.setFloat("depth", _this.depth);
  32498. effect.setFloat("colorLevel", _this.colorLevel);
  32499. effect.setTexture("refractionSampler", _this._refRexture);
  32500. };
  32501. }
  32502. // Methods
  32503. RefractionPostProcess.prototype.dispose = function (camera) {
  32504. if (this._refRexture) {
  32505. this._refRexture.dispose();
  32506. }
  32507. _super.prototype.dispose.call(this, camera);
  32508. };
  32509. return RefractionPostProcess;
  32510. })(BABYLON.PostProcess);
  32511. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32512. })(BABYLON || (BABYLON = {}));
  32513. var BABYLON;
  32514. (function (BABYLON) {
  32515. var BlackAndWhitePostProcess = (function (_super) {
  32516. __extends(BlackAndWhitePostProcess, _super);
  32517. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32518. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32519. }
  32520. return BlackAndWhitePostProcess;
  32521. })(BABYLON.PostProcess);
  32522. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32523. })(BABYLON || (BABYLON = {}));
  32524. var BABYLON;
  32525. (function (BABYLON) {
  32526. var ConvolutionPostProcess = (function (_super) {
  32527. __extends(ConvolutionPostProcess, _super);
  32528. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32529. var _this = this;
  32530. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32531. this.kernel = kernel;
  32532. this.onApply = function (effect) {
  32533. effect.setFloat2("screenSize", _this.width, _this.height);
  32534. effect.setArray("kernel", _this.kernel);
  32535. };
  32536. }
  32537. // Statics
  32538. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32539. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32540. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32541. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32542. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32543. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32544. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32545. return ConvolutionPostProcess;
  32546. })(BABYLON.PostProcess);
  32547. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32548. })(BABYLON || (BABYLON = {}));
  32549. var BABYLON;
  32550. (function (BABYLON) {
  32551. var FilterPostProcess = (function (_super) {
  32552. __extends(FilterPostProcess, _super);
  32553. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32554. var _this = this;
  32555. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32556. this.kernelMatrix = kernelMatrix;
  32557. this.onApply = function (effect) {
  32558. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32559. };
  32560. }
  32561. return FilterPostProcess;
  32562. })(BABYLON.PostProcess);
  32563. BABYLON.FilterPostProcess = FilterPostProcess;
  32564. })(BABYLON || (BABYLON = {}));
  32565. var BABYLON;
  32566. (function (BABYLON) {
  32567. var FxaaPostProcess = (function (_super) {
  32568. __extends(FxaaPostProcess, _super);
  32569. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32570. var _this = this;
  32571. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32572. this.onSizeChanged = function () {
  32573. _this.texelWidth = 1.0 / _this.width;
  32574. _this.texelHeight = 1.0 / _this.height;
  32575. };
  32576. this.onApply = function (effect) {
  32577. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32578. };
  32579. }
  32580. return FxaaPostProcess;
  32581. })(BABYLON.PostProcess);
  32582. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32583. })(BABYLON || (BABYLON = {}));
  32584. var BABYLON;
  32585. (function (BABYLON) {
  32586. var StereoscopicInterlacePostProcess = (function (_super) {
  32587. __extends(StereoscopicInterlacePostProcess, _super);
  32588. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32589. var _this = this;
  32590. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32591. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32592. this.onSizeChanged = function () {
  32593. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32594. };
  32595. this.onApply = function (effect) {
  32596. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32597. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32598. };
  32599. }
  32600. return StereoscopicInterlacePostProcess;
  32601. })(BABYLON.PostProcess);
  32602. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32603. })(BABYLON || (BABYLON = {}));
  32604. var BABYLON;
  32605. (function (BABYLON) {
  32606. var LensFlare = (function () {
  32607. function LensFlare(size, position, color, imgUrl, system) {
  32608. this.size = size;
  32609. this.position = position;
  32610. this.dispose = function () {
  32611. if (this.texture) {
  32612. this.texture.dispose();
  32613. }
  32614. // Remove from scene
  32615. var index = this._system.lensFlares.indexOf(this);
  32616. this._system.lensFlares.splice(index, 1);
  32617. };
  32618. this.color = color || new BABYLON.Color3(1, 1, 1);
  32619. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32620. this._system = system;
  32621. system.lensFlares.push(this);
  32622. }
  32623. return LensFlare;
  32624. })();
  32625. BABYLON.LensFlare = LensFlare;
  32626. })(BABYLON || (BABYLON = {}));
  32627. var BABYLON;
  32628. (function (BABYLON) {
  32629. var LensFlareSystem = (function () {
  32630. function LensFlareSystem(name, emitter, scene) {
  32631. this.name = name;
  32632. this.lensFlares = new Array();
  32633. this.borderLimit = 300;
  32634. this.layerMask = 0x0FFFFFFF;
  32635. this._vertexDeclaration = [2];
  32636. this._vertexStrideSize = 2 * 4;
  32637. this._isEnabled = true;
  32638. this._scene = scene;
  32639. this._emitter = emitter;
  32640. scene.lensFlareSystems.push(this);
  32641. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32642. // VBO
  32643. var vertices = [];
  32644. vertices.push(1, 1);
  32645. vertices.push(-1, 1);
  32646. vertices.push(-1, -1);
  32647. vertices.push(1, -1);
  32648. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32649. // Indices
  32650. var indices = [];
  32651. indices.push(0);
  32652. indices.push(1);
  32653. indices.push(2);
  32654. indices.push(0);
  32655. indices.push(2);
  32656. indices.push(3);
  32657. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32658. // Effects
  32659. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32660. }
  32661. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32662. get: function () {
  32663. return this._isEnabled;
  32664. },
  32665. set: function (value) {
  32666. this._isEnabled = value;
  32667. },
  32668. enumerable: true,
  32669. configurable: true
  32670. });
  32671. LensFlareSystem.prototype.getScene = function () {
  32672. return this._scene;
  32673. };
  32674. LensFlareSystem.prototype.getEmitter = function () {
  32675. return this._emitter;
  32676. };
  32677. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32678. this._emitter = newEmitter;
  32679. };
  32680. LensFlareSystem.prototype.getEmitterPosition = function () {
  32681. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32682. };
  32683. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32684. var position = this.getEmitterPosition();
  32685. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32686. this._positionX = position.x;
  32687. this._positionY = position.y;
  32688. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32689. if (position.z > 0) {
  32690. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32691. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32692. return true;
  32693. }
  32694. }
  32695. return false;
  32696. };
  32697. LensFlareSystem.prototype._isVisible = function () {
  32698. if (!this._isEnabled) {
  32699. return false;
  32700. }
  32701. var emitterPosition = this.getEmitterPosition();
  32702. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32703. var distance = direction.length();
  32704. direction.normalize();
  32705. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32706. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32707. return !pickInfo.hit || pickInfo.distance > distance;
  32708. };
  32709. LensFlareSystem.prototype.render = function () {
  32710. if (!this._effect.isReady())
  32711. return false;
  32712. var engine = this._scene.getEngine();
  32713. var viewport = this._scene.activeCamera.viewport;
  32714. var globalViewport = viewport.toScreenGlobal(engine);
  32715. // Position
  32716. if (!this.computeEffectivePosition(globalViewport)) {
  32717. return false;
  32718. }
  32719. // Visibility
  32720. if (!this._isVisible()) {
  32721. return false;
  32722. }
  32723. // Intensity
  32724. var awayX;
  32725. var awayY;
  32726. if (this._positionX < this.borderLimit + globalViewport.x) {
  32727. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32728. }
  32729. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32730. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32731. }
  32732. else {
  32733. awayX = 0;
  32734. }
  32735. if (this._positionY < this.borderLimit + globalViewport.y) {
  32736. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32737. }
  32738. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32739. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32740. }
  32741. else {
  32742. awayY = 0;
  32743. }
  32744. var away = (awayX > awayY) ? awayX : awayY;
  32745. if (away > this.borderLimit) {
  32746. away = this.borderLimit;
  32747. }
  32748. var intensity = 1.0 - (away / this.borderLimit);
  32749. if (intensity < 0) {
  32750. return false;
  32751. }
  32752. if (intensity > 1.0) {
  32753. intensity = 1.0;
  32754. }
  32755. // Position
  32756. var centerX = globalViewport.x + globalViewport.width / 2;
  32757. var centerY = globalViewport.y + globalViewport.height / 2;
  32758. var distX = centerX - this._positionX;
  32759. var distY = centerY - this._positionY;
  32760. // Effects
  32761. engine.enableEffect(this._effect);
  32762. engine.setState(false);
  32763. engine.setDepthBuffer(false);
  32764. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32765. // VBOs
  32766. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32767. // Flares
  32768. for (var index = 0; index < this.lensFlares.length; index++) {
  32769. var flare = this.lensFlares[index];
  32770. var x = centerX - (distX * flare.position);
  32771. var y = centerY - (distY * flare.position);
  32772. var cw = flare.size;
  32773. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  32774. var cx = 2 * (x / globalViewport.width) - 1.0;
  32775. var cy = 1.0 - 2 * (y / globalViewport.height);
  32776. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32777. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32778. // Texture
  32779. this._effect.setTexture("textureSampler", flare.texture);
  32780. // Color
  32781. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32782. // Draw order
  32783. engine.draw(true, 0, 6);
  32784. }
  32785. engine.setDepthBuffer(true);
  32786. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32787. return true;
  32788. };
  32789. LensFlareSystem.prototype.dispose = function () {
  32790. if (this._vertexBuffer) {
  32791. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32792. this._vertexBuffer = null;
  32793. }
  32794. if (this._indexBuffer) {
  32795. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32796. this._indexBuffer = null;
  32797. }
  32798. while (this.lensFlares.length) {
  32799. this.lensFlares[0].dispose();
  32800. }
  32801. // Remove from scene
  32802. var index = this._scene.lensFlareSystems.indexOf(this);
  32803. this._scene.lensFlareSystems.splice(index, 1);
  32804. };
  32805. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  32806. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32807. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32808. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32809. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32810. var parsedFlare = parsedLensFlareSystem.flares[index];
  32811. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32812. }
  32813. return lensFlareSystem;
  32814. };
  32815. LensFlareSystem.prototype.serialize = function () {
  32816. var serializationObject = {};
  32817. serializationObject.emitterId = this.getEmitter().id;
  32818. serializationObject.borderLimit = this.borderLimit;
  32819. serializationObject.flares = [];
  32820. for (var index = 0; index < this.lensFlares.length; index++) {
  32821. var flare = this.lensFlares[index];
  32822. serializationObject.flares.push({
  32823. size: flare.size,
  32824. position: flare.position,
  32825. color: flare.color.asArray(),
  32826. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32827. });
  32828. }
  32829. return serializationObject;
  32830. };
  32831. return LensFlareSystem;
  32832. })();
  32833. BABYLON.LensFlareSystem = LensFlareSystem;
  32834. })(BABYLON || (BABYLON = {}));
  32835. var BABYLON;
  32836. (function (BABYLON) {
  32837. // We're mainly based on the logic defined into the FreeCamera code
  32838. var DeviceOrientationCamera = (function (_super) {
  32839. __extends(DeviceOrientationCamera, _super);
  32840. function DeviceOrientationCamera(name, position, scene) {
  32841. var _this = this;
  32842. _super.call(this, name, position, scene);
  32843. this._offsetX = null;
  32844. this._offsetY = null;
  32845. this._orientationGamma = 0;
  32846. this._orientationBeta = 0;
  32847. this._initialOrientationGamma = 0;
  32848. this._initialOrientationBeta = 0;
  32849. this.angularSensibility = 10000.0;
  32850. this.moveSensibility = 50.0;
  32851. window.addEventListener("resize", function () {
  32852. _this._initialOrientationGamma = null;
  32853. }, false);
  32854. }
  32855. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32856. var _this = this;
  32857. if (this._attachedCanvas) {
  32858. return;
  32859. }
  32860. this._attachedCanvas = canvas;
  32861. if (!this._orientationChanged) {
  32862. this._orientationChanged = function (evt) {
  32863. if (!_this._initialOrientationGamma) {
  32864. _this._initialOrientationGamma = evt.gamma;
  32865. _this._initialOrientationBeta = evt.beta;
  32866. }
  32867. _this._orientationGamma = evt.gamma;
  32868. _this._orientationBeta = evt.beta;
  32869. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32870. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32871. };
  32872. }
  32873. window.addEventListener("deviceorientation", this._orientationChanged);
  32874. };
  32875. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32876. if (this._attachedCanvas !== canvas) {
  32877. return;
  32878. }
  32879. window.removeEventListener("deviceorientation", this._orientationChanged);
  32880. this._attachedCanvas = null;
  32881. this._orientationGamma = 0;
  32882. this._orientationBeta = 0;
  32883. this._initialOrientationGamma = 0;
  32884. this._initialOrientationBeta = 0;
  32885. };
  32886. DeviceOrientationCamera.prototype._checkInputs = function () {
  32887. if (!this._offsetX) {
  32888. return;
  32889. }
  32890. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32891. var speed = this._computeLocalCameraSpeed();
  32892. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32893. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32894. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32895. _super.prototype._checkInputs.call(this);
  32896. };
  32897. return DeviceOrientationCamera;
  32898. })(BABYLON.FreeCamera);
  32899. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32900. })(BABYLON || (BABYLON = {}));
  32901. var BABYLON;
  32902. (function (BABYLON) {
  32903. var Gamepads = (function () {
  32904. function Gamepads(ongamedpadconnected) {
  32905. var _this = this;
  32906. this.babylonGamepads = [];
  32907. this.oneGamepadConnected = false;
  32908. this.isMonitoring = false;
  32909. this.gamepadEventSupported = 'GamepadEvent' in window;
  32910. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32911. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32912. 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=";
  32913. this._callbackGamepadConnected = ongamedpadconnected;
  32914. if (this.gamepadSupportAvailable) {
  32915. // Checking if the gamepad connected event is supported (like in Firefox)
  32916. if (this.gamepadEventSupported) {
  32917. window.addEventListener('gamepadconnected', function (evt) {
  32918. _this._onGamepadConnected(evt);
  32919. }, false);
  32920. window.addEventListener('gamepaddisconnected', function (evt) {
  32921. _this._onGamepadDisconnected(evt);
  32922. }, false);
  32923. }
  32924. else {
  32925. this._startMonitoringGamepads();
  32926. }
  32927. if (!this.oneGamepadConnected) {
  32928. this._insertGamepadDOMInstructions();
  32929. }
  32930. }
  32931. else {
  32932. this._insertGamepadDOMNotSupported();
  32933. }
  32934. }
  32935. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32936. Gamepads.gamepadDOMInfo = document.createElement("div");
  32937. var buttonAImage = document.createElement("img");
  32938. buttonAImage.src = this.buttonADataURL;
  32939. var spanMessage = document.createElement("span");
  32940. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32941. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32942. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32943. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32944. Gamepads.gamepadDOMInfo.style.width = "100%";
  32945. Gamepads.gamepadDOMInfo.style.height = "48px";
  32946. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32947. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32948. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32949. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32950. buttonAImage.style.position = "relative";
  32951. buttonAImage.style.bottom = "8px";
  32952. spanMessage.style.position = "relative";
  32953. spanMessage.style.fontSize = "32px";
  32954. spanMessage.style.bottom = "32px";
  32955. spanMessage.style.color = "green";
  32956. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32957. };
  32958. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32959. Gamepads.gamepadDOMInfo = document.createElement("div");
  32960. var spanMessage = document.createElement("span");
  32961. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32962. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32963. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32964. Gamepads.gamepadDOMInfo.style.width = "100%";
  32965. Gamepads.gamepadDOMInfo.style.height = "40px";
  32966. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32967. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32968. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32969. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32970. spanMessage.style.position = "relative";
  32971. spanMessage.style.fontSize = "32px";
  32972. spanMessage.style.color = "red";
  32973. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32974. };
  32975. Gamepads.prototype.dispose = function () {
  32976. if (Gamepads.gamepadDOMInfo) {
  32977. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32978. }
  32979. };
  32980. Gamepads.prototype._onGamepadConnected = function (evt) {
  32981. var newGamepad = this._addNewGamepad(evt.gamepad);
  32982. if (this._callbackGamepadConnected)
  32983. this._callbackGamepadConnected(newGamepad);
  32984. this._startMonitoringGamepads();
  32985. };
  32986. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32987. if (!this.oneGamepadConnected) {
  32988. this.oneGamepadConnected = true;
  32989. if (Gamepads.gamepadDOMInfo) {
  32990. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32991. Gamepads.gamepadDOMInfo = null;
  32992. }
  32993. }
  32994. var newGamepad;
  32995. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32996. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32997. }
  32998. else {
  32999. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33000. }
  33001. this.babylonGamepads.push(newGamepad);
  33002. return newGamepad;
  33003. };
  33004. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33005. // Remove the gamepad from the list of gamepads to monitor.
  33006. for (var i in this.babylonGamepads) {
  33007. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33008. this.babylonGamepads.splice(i, 1);
  33009. break;
  33010. }
  33011. }
  33012. // If no gamepads are left, stop the polling loop.
  33013. if (this.babylonGamepads.length == 0) {
  33014. this._stopMonitoringGamepads();
  33015. }
  33016. };
  33017. Gamepads.prototype._startMonitoringGamepads = function () {
  33018. if (!this.isMonitoring) {
  33019. this.isMonitoring = true;
  33020. this._checkGamepadsStatus();
  33021. }
  33022. };
  33023. Gamepads.prototype._stopMonitoringGamepads = function () {
  33024. this.isMonitoring = false;
  33025. };
  33026. Gamepads.prototype._checkGamepadsStatus = function () {
  33027. var _this = this;
  33028. // updating gamepad objects
  33029. this._updateGamepadObjects();
  33030. for (var i in this.babylonGamepads) {
  33031. this.babylonGamepads[i].update();
  33032. }
  33033. if (this.isMonitoring) {
  33034. if (window.requestAnimationFrame) {
  33035. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33036. }
  33037. else if (window.mozRequestAnimationFrame) {
  33038. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33039. }
  33040. else if (window.webkitRequestAnimationFrame) {
  33041. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33042. }
  33043. }
  33044. };
  33045. // This function is called only on Chrome, which does not yet support
  33046. // connection/disconnection events, but requires you to monitor
  33047. // an array for changes.
  33048. Gamepads.prototype._updateGamepadObjects = function () {
  33049. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33050. for (var i = 0; i < gamepads.length; i++) {
  33051. if (gamepads[i]) {
  33052. if (!(gamepads[i].index in this.babylonGamepads)) {
  33053. var newGamepad = this._addNewGamepad(gamepads[i]);
  33054. if (this._callbackGamepadConnected) {
  33055. this._callbackGamepadConnected(newGamepad);
  33056. }
  33057. }
  33058. else {
  33059. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33060. }
  33061. }
  33062. }
  33063. };
  33064. return Gamepads;
  33065. })();
  33066. BABYLON.Gamepads = Gamepads;
  33067. var StickValues = (function () {
  33068. function StickValues(x, y) {
  33069. this.x = x;
  33070. this.y = y;
  33071. }
  33072. return StickValues;
  33073. })();
  33074. BABYLON.StickValues = StickValues;
  33075. var Gamepad = (function () {
  33076. function Gamepad(id, index, browserGamepad) {
  33077. this.id = id;
  33078. this.index = index;
  33079. this.browserGamepad = browserGamepad;
  33080. if (this.browserGamepad.axes.length >= 2) {
  33081. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33082. }
  33083. if (this.browserGamepad.axes.length >= 4) {
  33084. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33085. }
  33086. }
  33087. Gamepad.prototype.onleftstickchanged = function (callback) {
  33088. this._onleftstickchanged = callback;
  33089. };
  33090. Gamepad.prototype.onrightstickchanged = function (callback) {
  33091. this._onrightstickchanged = callback;
  33092. };
  33093. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33094. get: function () {
  33095. return this._leftStick;
  33096. },
  33097. set: function (newValues) {
  33098. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33099. this._onleftstickchanged(newValues);
  33100. }
  33101. this._leftStick = newValues;
  33102. },
  33103. enumerable: true,
  33104. configurable: true
  33105. });
  33106. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33107. get: function () {
  33108. return this._rightStick;
  33109. },
  33110. set: function (newValues) {
  33111. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33112. this._onrightstickchanged(newValues);
  33113. }
  33114. this._rightStick = newValues;
  33115. },
  33116. enumerable: true,
  33117. configurable: true
  33118. });
  33119. Gamepad.prototype.update = function () {
  33120. if (this._leftStick) {
  33121. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33122. }
  33123. if (this._rightStick) {
  33124. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33125. }
  33126. };
  33127. return Gamepad;
  33128. })();
  33129. BABYLON.Gamepad = Gamepad;
  33130. var GenericPad = (function (_super) {
  33131. __extends(GenericPad, _super);
  33132. function GenericPad(id, index, gamepad) {
  33133. _super.call(this, id, index, gamepad);
  33134. this.id = id;
  33135. this.index = index;
  33136. this.gamepad = gamepad;
  33137. this._buttons = new Array(gamepad.buttons.length);
  33138. }
  33139. GenericPad.prototype.onbuttondown = function (callback) {
  33140. this._onbuttondown = callback;
  33141. };
  33142. GenericPad.prototype.onbuttonup = function (callback) {
  33143. this._onbuttonup = callback;
  33144. };
  33145. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33146. if (newValue !== currentValue) {
  33147. if (this._onbuttondown && newValue === 1) {
  33148. this._onbuttondown(buttonIndex);
  33149. }
  33150. if (this._onbuttonup && newValue === 0) {
  33151. this._onbuttonup(buttonIndex);
  33152. }
  33153. }
  33154. return newValue;
  33155. };
  33156. GenericPad.prototype.update = function () {
  33157. _super.prototype.update.call(this);
  33158. for (var index = 0; index < this._buttons.length; index++) {
  33159. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33160. }
  33161. };
  33162. return GenericPad;
  33163. })(Gamepad);
  33164. BABYLON.GenericPad = GenericPad;
  33165. (function (Xbox360Button) {
  33166. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33167. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33168. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33169. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33170. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33171. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33172. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33173. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33174. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33175. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33176. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33177. var Xbox360Button = BABYLON.Xbox360Button;
  33178. (function (Xbox360Dpad) {
  33179. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33180. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33181. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33182. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33183. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33184. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33185. var Xbox360Pad = (function (_super) {
  33186. __extends(Xbox360Pad, _super);
  33187. function Xbox360Pad() {
  33188. _super.apply(this, arguments);
  33189. this._leftTrigger = 0;
  33190. this._rightTrigger = 0;
  33191. this._buttonA = 0;
  33192. this._buttonB = 0;
  33193. this._buttonX = 0;
  33194. this._buttonY = 0;
  33195. this._buttonBack = 0;
  33196. this._buttonStart = 0;
  33197. this._buttonLB = 0;
  33198. this._buttonRB = 0;
  33199. this._buttonLeftStick = 0;
  33200. this._buttonRightStick = 0;
  33201. this._dPadUp = 0;
  33202. this._dPadDown = 0;
  33203. this._dPadLeft = 0;
  33204. this._dPadRight = 0;
  33205. }
  33206. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33207. this._onlefttriggerchanged = callback;
  33208. };
  33209. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33210. this._onrighttriggerchanged = callback;
  33211. };
  33212. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33213. get: function () {
  33214. return this._leftTrigger;
  33215. },
  33216. set: function (newValue) {
  33217. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33218. this._onlefttriggerchanged(newValue);
  33219. }
  33220. this._leftTrigger = newValue;
  33221. },
  33222. enumerable: true,
  33223. configurable: true
  33224. });
  33225. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33226. get: function () {
  33227. return this._rightTrigger;
  33228. },
  33229. set: function (newValue) {
  33230. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33231. this._onrighttriggerchanged(newValue);
  33232. }
  33233. this._rightTrigger = newValue;
  33234. },
  33235. enumerable: true,
  33236. configurable: true
  33237. });
  33238. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33239. this._onbuttondown = callback;
  33240. };
  33241. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33242. this._onbuttonup = callback;
  33243. };
  33244. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33245. this._ondpaddown = callback;
  33246. };
  33247. Xbox360Pad.prototype.ondpadup = function (callback) {
  33248. this._ondpadup = callback;
  33249. };
  33250. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33251. if (newValue !== currentValue) {
  33252. if (this._onbuttondown && newValue === 1) {
  33253. this._onbuttondown(buttonType);
  33254. }
  33255. if (this._onbuttonup && newValue === 0) {
  33256. this._onbuttonup(buttonType);
  33257. }
  33258. }
  33259. return newValue;
  33260. };
  33261. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33262. if (newValue !== currentValue) {
  33263. if (this._ondpaddown && newValue === 1) {
  33264. this._ondpaddown(buttonType);
  33265. }
  33266. if (this._ondpadup && newValue === 0) {
  33267. this._ondpadup(buttonType);
  33268. }
  33269. }
  33270. return newValue;
  33271. };
  33272. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33273. get: function () {
  33274. return this._buttonA;
  33275. },
  33276. set: function (value) {
  33277. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33278. },
  33279. enumerable: true,
  33280. configurable: true
  33281. });
  33282. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33283. get: function () {
  33284. return this._buttonB;
  33285. },
  33286. set: function (value) {
  33287. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33288. },
  33289. enumerable: true,
  33290. configurable: true
  33291. });
  33292. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33293. get: function () {
  33294. return this._buttonX;
  33295. },
  33296. set: function (value) {
  33297. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33298. },
  33299. enumerable: true,
  33300. configurable: true
  33301. });
  33302. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33303. get: function () {
  33304. return this._buttonY;
  33305. },
  33306. set: function (value) {
  33307. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33308. },
  33309. enumerable: true,
  33310. configurable: true
  33311. });
  33312. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33313. get: function () {
  33314. return this._buttonStart;
  33315. },
  33316. set: function (value) {
  33317. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33318. },
  33319. enumerable: true,
  33320. configurable: true
  33321. });
  33322. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33323. get: function () {
  33324. return this._buttonBack;
  33325. },
  33326. set: function (value) {
  33327. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33328. },
  33329. enumerable: true,
  33330. configurable: true
  33331. });
  33332. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33333. get: function () {
  33334. return this._buttonLB;
  33335. },
  33336. set: function (value) {
  33337. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33338. },
  33339. enumerable: true,
  33340. configurable: true
  33341. });
  33342. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33343. get: function () {
  33344. return this._buttonRB;
  33345. },
  33346. set: function (value) {
  33347. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33348. },
  33349. enumerable: true,
  33350. configurable: true
  33351. });
  33352. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33353. get: function () {
  33354. return this._buttonLeftStick;
  33355. },
  33356. set: function (value) {
  33357. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33358. },
  33359. enumerable: true,
  33360. configurable: true
  33361. });
  33362. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33363. get: function () {
  33364. return this._buttonRightStick;
  33365. },
  33366. set: function (value) {
  33367. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33368. },
  33369. enumerable: true,
  33370. configurable: true
  33371. });
  33372. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33373. get: function () {
  33374. return this._dPadUp;
  33375. },
  33376. set: function (value) {
  33377. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33378. },
  33379. enumerable: true,
  33380. configurable: true
  33381. });
  33382. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33383. get: function () {
  33384. return this._dPadDown;
  33385. },
  33386. set: function (value) {
  33387. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33388. },
  33389. enumerable: true,
  33390. configurable: true
  33391. });
  33392. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33393. get: function () {
  33394. return this._dPadLeft;
  33395. },
  33396. set: function (value) {
  33397. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33398. },
  33399. enumerable: true,
  33400. configurable: true
  33401. });
  33402. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33403. get: function () {
  33404. return this._dPadRight;
  33405. },
  33406. set: function (value) {
  33407. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. Xbox360Pad.prototype.update = function () {
  33413. _super.prototype.update.call(this);
  33414. this.buttonA = this.browserGamepad.buttons[0].value;
  33415. this.buttonB = this.browserGamepad.buttons[1].value;
  33416. this.buttonX = this.browserGamepad.buttons[2].value;
  33417. this.buttonY = this.browserGamepad.buttons[3].value;
  33418. this.buttonLB = this.browserGamepad.buttons[4].value;
  33419. this.buttonRB = this.browserGamepad.buttons[5].value;
  33420. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33421. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33422. this.buttonBack = this.browserGamepad.buttons[8].value;
  33423. this.buttonStart = this.browserGamepad.buttons[9].value;
  33424. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33425. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33426. this.dPadUp = this.browserGamepad.buttons[12].value;
  33427. this.dPadDown = this.browserGamepad.buttons[13].value;
  33428. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33429. this.dPadRight = this.browserGamepad.buttons[15].value;
  33430. };
  33431. return Xbox360Pad;
  33432. })(Gamepad);
  33433. BABYLON.Xbox360Pad = Xbox360Pad;
  33434. })(BABYLON || (BABYLON = {}));
  33435. var BABYLON;
  33436. (function (BABYLON) {
  33437. // We're mainly based on the logic defined into the FreeCamera code
  33438. var GamepadCamera = (function (_super) {
  33439. __extends(GamepadCamera, _super);
  33440. function GamepadCamera(name, position, scene) {
  33441. var _this = this;
  33442. _super.call(this, name, position, scene);
  33443. this.angularSensibility = 200;
  33444. this.moveSensibility = 75;
  33445. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33446. }
  33447. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33448. // Only the first gamepad can control the camera
  33449. if (gamepad.index === 0) {
  33450. this._gamepad = gamepad;
  33451. }
  33452. };
  33453. GamepadCamera.prototype._checkInputs = function () {
  33454. if (this._gamepad) {
  33455. var LSValues = this._gamepad.leftStick;
  33456. var normalizedLX = LSValues.x / this.moveSensibility;
  33457. var normalizedLY = LSValues.y / this.moveSensibility;
  33458. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33459. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33460. var RSValues = this._gamepad.rightStick;
  33461. var normalizedRX = RSValues.x / this.angularSensibility;
  33462. var normalizedRY = RSValues.y / this.angularSensibility;
  33463. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33464. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33465. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33466. var speed = this._computeLocalCameraSpeed() * 50.0;
  33467. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33468. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33469. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33470. }
  33471. _super.prototype._checkInputs.call(this);
  33472. };
  33473. GamepadCamera.prototype.dispose = function () {
  33474. this._gamepads.dispose();
  33475. _super.prototype.dispose.call(this);
  33476. };
  33477. return GamepadCamera;
  33478. })(BABYLON.FreeCamera);
  33479. BABYLON.GamepadCamera = GamepadCamera;
  33480. })(BABYLON || (BABYLON = {}));
  33481. var BABYLON;
  33482. (function (BABYLON) {
  33483. var Analyser = (function () {
  33484. function Analyser(scene) {
  33485. this.SMOOTHING = 0.75;
  33486. this.FFT_SIZE = 512;
  33487. this.BARGRAPHAMPLITUDE = 256;
  33488. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33489. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33490. this._scene = scene;
  33491. this._audioEngine = BABYLON.Engine.audioEngine;
  33492. if (this._audioEngine.canUseWebAudio) {
  33493. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33494. this._webAudioAnalyser.minDecibels = -140;
  33495. this._webAudioAnalyser.maxDecibels = 0;
  33496. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33497. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33498. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33499. }
  33500. }
  33501. Analyser.prototype.getFrequencyBinCount = function () {
  33502. if (this._audioEngine.canUseWebAudio) {
  33503. return this._webAudioAnalyser.frequencyBinCount;
  33504. }
  33505. else {
  33506. return 0;
  33507. }
  33508. };
  33509. Analyser.prototype.getByteFrequencyData = function () {
  33510. if (this._audioEngine.canUseWebAudio) {
  33511. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33512. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33513. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33514. }
  33515. return this._byteFreqs;
  33516. };
  33517. Analyser.prototype.getByteTimeDomainData = function () {
  33518. if (this._audioEngine.canUseWebAudio) {
  33519. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33520. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33521. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33522. }
  33523. return this._byteTime;
  33524. };
  33525. Analyser.prototype.getFloatFrequencyData = function () {
  33526. if (this._audioEngine.canUseWebAudio) {
  33527. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33528. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33529. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33530. }
  33531. return this._floatFreqs;
  33532. };
  33533. Analyser.prototype.drawDebugCanvas = function () {
  33534. var _this = this;
  33535. if (this._audioEngine.canUseWebAudio) {
  33536. if (!this._debugCanvas) {
  33537. this._debugCanvas = document.createElement("canvas");
  33538. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33539. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33540. this._debugCanvas.style.position = "absolute";
  33541. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33542. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33543. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33544. document.body.appendChild(this._debugCanvas);
  33545. this._registerFunc = function () {
  33546. _this.drawDebugCanvas();
  33547. };
  33548. this._scene.registerBeforeRender(this._registerFunc);
  33549. }
  33550. if (this._registerFunc) {
  33551. var workingArray = this.getByteFrequencyData();
  33552. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33553. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33554. // Draw the frequency domain chart.
  33555. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33556. var value = workingArray[i];
  33557. var percent = value / this.BARGRAPHAMPLITUDE;
  33558. var height = this.DEBUGCANVASSIZE.height * percent;
  33559. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33560. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33561. var hue = i / this.getFrequencyBinCount() * 360;
  33562. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33563. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33564. }
  33565. }
  33566. }
  33567. };
  33568. Analyser.prototype.stopDebugCanvas = function () {
  33569. if (this._debugCanvas) {
  33570. this._scene.unregisterBeforeRender(this._registerFunc);
  33571. this._registerFunc = null;
  33572. document.body.removeChild(this._debugCanvas);
  33573. this._debugCanvas = null;
  33574. this._debugCanvasContext = null;
  33575. }
  33576. };
  33577. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33578. if (this._audioEngine.canUseWebAudio) {
  33579. inputAudioNode.connect(this._webAudioAnalyser);
  33580. this._webAudioAnalyser.connect(outputAudioNode);
  33581. }
  33582. };
  33583. Analyser.prototype.dispose = function () {
  33584. if (this._audioEngine.canUseWebAudio) {
  33585. this._webAudioAnalyser.disconnect();
  33586. }
  33587. };
  33588. return Analyser;
  33589. })();
  33590. BABYLON.Analyser = Analyser;
  33591. })(BABYLON || (BABYLON = {}));
  33592. var BABYLON;
  33593. (function (BABYLON) {
  33594. var AudioEngine = (function () {
  33595. function AudioEngine() {
  33596. this._audioContext = null;
  33597. this._audioContextInitialized = false;
  33598. this.canUseWebAudio = false;
  33599. this.WarnedWebAudioUnsupported = false;
  33600. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33601. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33602. this.canUseWebAudio = true;
  33603. }
  33604. }
  33605. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33606. get: function () {
  33607. if (!this._audioContextInitialized) {
  33608. this._initializeAudioContext();
  33609. }
  33610. return this._audioContext;
  33611. },
  33612. enumerable: true,
  33613. configurable: true
  33614. });
  33615. AudioEngine.prototype._initializeAudioContext = function () {
  33616. try {
  33617. if (this.canUseWebAudio) {
  33618. this._audioContext = new AudioContext();
  33619. // create a global volume gain node
  33620. this.masterGain = this._audioContext.createGain();
  33621. this.masterGain.gain.value = 1;
  33622. this.masterGain.connect(this._audioContext.destination);
  33623. this._audioContextInitialized = true;
  33624. }
  33625. }
  33626. catch (e) {
  33627. this.canUseWebAudio = false;
  33628. BABYLON.Tools.Error("Web Audio: " + e.message);
  33629. }
  33630. };
  33631. AudioEngine.prototype.dispose = function () {
  33632. if (this.canUseWebAudio && this._audioContextInitialized) {
  33633. if (this._connectedAnalyser) {
  33634. this._connectedAnalyser.stopDebugCanvas();
  33635. this._connectedAnalyser.dispose();
  33636. this.masterGain.disconnect();
  33637. this.masterGain.connect(this._audioContext.destination);
  33638. this._connectedAnalyser = null;
  33639. }
  33640. this.masterGain.gain.value = 1;
  33641. }
  33642. this.WarnedWebAudioUnsupported = false;
  33643. };
  33644. AudioEngine.prototype.getGlobalVolume = function () {
  33645. if (this.canUseWebAudio && this._audioContextInitialized) {
  33646. return this.masterGain.gain.value;
  33647. }
  33648. else {
  33649. return -1;
  33650. }
  33651. };
  33652. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33653. if (this.canUseWebAudio && this._audioContextInitialized) {
  33654. this.masterGain.gain.value = newVolume;
  33655. }
  33656. };
  33657. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33658. if (this._connectedAnalyser) {
  33659. this._connectedAnalyser.stopDebugCanvas();
  33660. }
  33661. if (this.canUseWebAudio && this._audioContextInitialized) {
  33662. this._connectedAnalyser = analyser;
  33663. this.masterGain.disconnect();
  33664. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33665. }
  33666. };
  33667. return AudioEngine;
  33668. })();
  33669. BABYLON.AudioEngine = AudioEngine;
  33670. })(BABYLON || (BABYLON = {}));
  33671. var BABYLON;
  33672. (function (BABYLON) {
  33673. var Sound = (function () {
  33674. /**
  33675. * Create a sound and attach it to a scene
  33676. * @param name Name of your sound
  33677. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33678. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33679. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33680. */
  33681. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33682. var _this = this;
  33683. this.autoplay = false;
  33684. this.loop = false;
  33685. this.useCustomAttenuation = false;
  33686. this.spatialSound = false;
  33687. this.refDistance = 1;
  33688. this.rolloffFactor = 1;
  33689. this.maxDistance = 100;
  33690. this.distanceModel = "linear";
  33691. this._panningModel = "equalpower";
  33692. this._playbackRate = 1;
  33693. this._streaming = false;
  33694. this._startTime = 0;
  33695. this._startOffset = 0;
  33696. this._position = BABYLON.Vector3.Zero();
  33697. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33698. this._volume = 1;
  33699. this._isLoaded = false;
  33700. this._isReadyToPlay = false;
  33701. this.isPlaying = false;
  33702. this.isPaused = false;
  33703. this._isDirectional = false;
  33704. // Used if you'd like to create a directional sound.
  33705. // If not set, the sound will be omnidirectional
  33706. this._coneInnerAngle = 360;
  33707. this._coneOuterAngle = 360;
  33708. this._coneOuterGain = 0;
  33709. this._isOutputConnected = false;
  33710. this.name = name;
  33711. this._scene = scene;
  33712. this._readyToPlayCallback = readyToPlayCallback;
  33713. // Default custom attenuation function is a linear attenuation
  33714. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33715. if (currentDistance < maxDistance) {
  33716. return currentVolume * (1 - currentDistance / maxDistance);
  33717. }
  33718. else {
  33719. return 0;
  33720. }
  33721. };
  33722. if (options) {
  33723. this.autoplay = options.autoplay || false;
  33724. this.loop = options.loop || false;
  33725. // if volume === 0, we need another way to check this option
  33726. if (options.volume !== undefined) {
  33727. this._volume = options.volume;
  33728. }
  33729. this.spatialSound = options.spatialSound || false;
  33730. this.maxDistance = options.maxDistance || 100;
  33731. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33732. this.rolloffFactor = options.rolloffFactor || 1;
  33733. this.refDistance = options.refDistance || 1;
  33734. this.distanceModel = options.distanceModel || "linear";
  33735. this._playbackRate = options.playbackRate || 1;
  33736. this._streaming = options.streaming || false;
  33737. }
  33738. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33739. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33740. this._soundGain.gain.value = this._volume;
  33741. this._inputAudioNode = this._soundGain;
  33742. this._ouputAudioNode = this._soundGain;
  33743. if (this.spatialSound) {
  33744. this._createSpatialParameters();
  33745. }
  33746. this._scene.mainSoundTrack.AddSound(this);
  33747. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33748. if (urlOrArrayBuffer) {
  33749. // If it's an URL
  33750. if (typeof (urlOrArrayBuffer) === "string") {
  33751. // Loading sound using XHR2
  33752. if (!this._streaming) {
  33753. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33754. }
  33755. else {
  33756. this._htmlAudioElement = new Audio();
  33757. this._htmlAudioElement.src = urlOrArrayBuffer;
  33758. this._htmlAudioElement.controls = false;
  33759. this._htmlAudioElement.loop = this.loop;
  33760. this._htmlAudioElement.crossOrigin = "anonymous";
  33761. this._isReadyToPlay = true;
  33762. document.body.appendChild(this._htmlAudioElement);
  33763. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33764. if (this._readyToPlayCallback) {
  33765. window.setTimeout(function () {
  33766. _this._readyToPlayCallback();
  33767. }, 1000);
  33768. }
  33769. if (this.autoplay) {
  33770. this.play();
  33771. }
  33772. }
  33773. }
  33774. else {
  33775. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33776. this._soundLoaded(urlOrArrayBuffer);
  33777. }
  33778. else {
  33779. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33780. }
  33781. }
  33782. }
  33783. }
  33784. else {
  33785. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33786. this._scene.mainSoundTrack.AddSound(this);
  33787. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33788. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33789. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33790. }
  33791. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33792. if (this._readyToPlayCallback) {
  33793. window.setTimeout(function () {
  33794. _this._readyToPlayCallback();
  33795. }, 1000);
  33796. }
  33797. }
  33798. }
  33799. Sound.prototype.dispose = function () {
  33800. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33801. if (this.isPlaying) {
  33802. this.stop();
  33803. }
  33804. this._isReadyToPlay = false;
  33805. if (this.soundTrackId === -1) {
  33806. this._scene.mainSoundTrack.RemoveSound(this);
  33807. }
  33808. else {
  33809. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33810. }
  33811. if (this._soundGain) {
  33812. this._soundGain.disconnect();
  33813. this._soundGain = null;
  33814. }
  33815. if (this._soundPanner) {
  33816. this._soundPanner.disconnect();
  33817. this._soundPanner = null;
  33818. }
  33819. if (this._soundSource) {
  33820. this._soundSource.disconnect();
  33821. this._soundSource = null;
  33822. }
  33823. this._audioBuffer = null;
  33824. if (this._htmlAudioElement) {
  33825. this._htmlAudioElement.pause();
  33826. this._htmlAudioElement.src = "";
  33827. document.body.removeChild(this._htmlAudioElement);
  33828. }
  33829. if (this._connectedMesh) {
  33830. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33831. this._connectedMesh = null;
  33832. }
  33833. }
  33834. };
  33835. Sound.prototype._soundLoaded = function (audioData) {
  33836. var _this = this;
  33837. this._isLoaded = true;
  33838. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33839. _this._audioBuffer = buffer;
  33840. _this._isReadyToPlay = true;
  33841. if (_this.autoplay) {
  33842. _this.play();
  33843. }
  33844. if (_this._readyToPlayCallback) {
  33845. _this._readyToPlayCallback();
  33846. }
  33847. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33848. };
  33849. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33850. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33851. this._audioBuffer = audioBuffer;
  33852. this._isReadyToPlay = true;
  33853. }
  33854. };
  33855. Sound.prototype.updateOptions = function (options) {
  33856. if (options) {
  33857. this.loop = options.loop || this.loop;
  33858. this.maxDistance = options.maxDistance || this.maxDistance;
  33859. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33860. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33861. this.refDistance = options.refDistance || this.refDistance;
  33862. this.distanceModel = options.distanceModel || this.distanceModel;
  33863. this._playbackRate = options.playbackRate || this._playbackRate;
  33864. this._updateSpatialParameters();
  33865. if (this.isPlaying) {
  33866. if (this._streaming) {
  33867. this._htmlAudioElement.playbackRate = this._playbackRate;
  33868. }
  33869. else {
  33870. this._soundSource.playbackRate.value = this._playbackRate;
  33871. }
  33872. }
  33873. }
  33874. };
  33875. Sound.prototype._createSpatialParameters = function () {
  33876. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33877. if (this._scene.headphone) {
  33878. this._panningModel = "HRTF";
  33879. }
  33880. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33881. this._updateSpatialParameters();
  33882. this._soundPanner.connect(this._ouputAudioNode);
  33883. this._inputAudioNode = this._soundPanner;
  33884. }
  33885. };
  33886. Sound.prototype._updateSpatialParameters = function () {
  33887. if (this.spatialSound) {
  33888. if (this.useCustomAttenuation) {
  33889. // Tricks to disable in a way embedded Web Audio attenuation
  33890. this._soundPanner.distanceModel = "linear";
  33891. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33892. this._soundPanner.refDistance = 1;
  33893. this._soundPanner.rolloffFactor = 1;
  33894. this._soundPanner.panningModel = this._panningModel;
  33895. }
  33896. else {
  33897. this._soundPanner.distanceModel = this.distanceModel;
  33898. this._soundPanner.maxDistance = this.maxDistance;
  33899. this._soundPanner.refDistance = this.refDistance;
  33900. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33901. this._soundPanner.panningModel = this._panningModel;
  33902. }
  33903. }
  33904. };
  33905. Sound.prototype.switchPanningModelToHRTF = function () {
  33906. this._panningModel = "HRTF";
  33907. this._switchPanningModel();
  33908. };
  33909. Sound.prototype.switchPanningModelToEqualPower = function () {
  33910. this._panningModel = "equalpower";
  33911. this._switchPanningModel();
  33912. };
  33913. Sound.prototype._switchPanningModel = function () {
  33914. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33915. this._soundPanner.panningModel = this._panningModel;
  33916. }
  33917. };
  33918. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33920. if (this._isOutputConnected) {
  33921. this._ouputAudioNode.disconnect();
  33922. }
  33923. this._ouputAudioNode.connect(soundTrackAudioNode);
  33924. this._isOutputConnected = true;
  33925. }
  33926. };
  33927. /**
  33928. * Transform this sound into a directional source
  33929. * @param coneInnerAngle Size of the inner cone in degree
  33930. * @param coneOuterAngle Size of the outer cone in degree
  33931. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33932. */
  33933. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33934. if (coneOuterAngle < coneInnerAngle) {
  33935. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33936. return;
  33937. }
  33938. this._coneInnerAngle = coneInnerAngle;
  33939. this._coneOuterAngle = coneOuterAngle;
  33940. this._coneOuterGain = coneOuterGain;
  33941. this._isDirectional = true;
  33942. if (this.isPlaying && this.loop) {
  33943. this.stop();
  33944. this.play();
  33945. }
  33946. };
  33947. Sound.prototype.setPosition = function (newPosition) {
  33948. this._position = newPosition;
  33949. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33950. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33951. }
  33952. };
  33953. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33954. this._localDirection = newLocalDirection;
  33955. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33956. this._updateDirection();
  33957. }
  33958. };
  33959. Sound.prototype._updateDirection = function () {
  33960. var mat = this._connectedMesh.getWorldMatrix();
  33961. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33962. direction.normalize();
  33963. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33964. };
  33965. Sound.prototype.updateDistanceFromListener = function () {
  33966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33967. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33968. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33969. }
  33970. };
  33971. Sound.prototype.setAttenuationFunction = function (callback) {
  33972. this._customAttenuationFunction = callback;
  33973. };
  33974. /**
  33975. * Play the sound
  33976. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33977. */
  33978. Sound.prototype.play = function (time) {
  33979. var _this = this;
  33980. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33981. try {
  33982. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33983. if (!this._soundSource || !this._streamingSource) {
  33984. if (this.spatialSound) {
  33985. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33986. if (this._isDirectional) {
  33987. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33988. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33989. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33990. if (this._connectedMesh) {
  33991. this._updateDirection();
  33992. }
  33993. else {
  33994. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33995. }
  33996. }
  33997. }
  33998. }
  33999. if (this._streaming) {
  34000. if (!this._streamingSource) {
  34001. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34002. this._htmlAudioElement.onended = function () { _this._onended(); };
  34003. this._htmlAudioElement.playbackRate = this._playbackRate;
  34004. }
  34005. this._streamingSource.disconnect();
  34006. this._streamingSource.connect(this._inputAudioNode);
  34007. this._htmlAudioElement.play();
  34008. }
  34009. else {
  34010. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34011. this._soundSource.buffer = this._audioBuffer;
  34012. this._soundSource.connect(this._inputAudioNode);
  34013. this._soundSource.loop = this.loop;
  34014. this._soundSource.playbackRate.value = this._playbackRate;
  34015. this._soundSource.onended = function () { _this._onended(); };
  34016. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34017. }
  34018. this._startTime = startTime;
  34019. this.isPlaying = true;
  34020. this.isPaused = false;
  34021. }
  34022. catch (ex) {
  34023. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34024. }
  34025. }
  34026. };
  34027. Sound.prototype._onended = function () {
  34028. this.isPlaying = false;
  34029. if (this.onended) {
  34030. this.onended();
  34031. }
  34032. };
  34033. /**
  34034. * Stop the sound
  34035. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34036. */
  34037. Sound.prototype.stop = function (time) {
  34038. if (this.isPlaying) {
  34039. if (this._streaming) {
  34040. this._htmlAudioElement.pause();
  34041. // Test needed for Firefox or it will generate an Invalid State Error
  34042. if (this._htmlAudioElement.currentTime > 0) {
  34043. this._htmlAudioElement.currentTime = 0;
  34044. }
  34045. }
  34046. else {
  34047. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34048. this._soundSource.stop(stopTime);
  34049. }
  34050. this.isPlaying = false;
  34051. }
  34052. };
  34053. Sound.prototype.pause = function () {
  34054. if (this.isPlaying) {
  34055. if (this._streaming) {
  34056. this._htmlAudioElement.pause();
  34057. }
  34058. else {
  34059. this.stop(0);
  34060. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34061. }
  34062. this.isPaused = true;
  34063. }
  34064. };
  34065. Sound.prototype.setVolume = function (newVolume, time) {
  34066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34067. if (time) {
  34068. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34069. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34070. }
  34071. else {
  34072. this._soundGain.gain.value = newVolume;
  34073. }
  34074. }
  34075. this._volume = newVolume;
  34076. };
  34077. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34078. this._playbackRate = newPlaybackRate;
  34079. if (this.isPlaying) {
  34080. if (this._streaming) {
  34081. this._htmlAudioElement.playbackRate = this._playbackRate;
  34082. }
  34083. else {
  34084. this._soundSource.playbackRate.value = this._playbackRate;
  34085. }
  34086. }
  34087. };
  34088. Sound.prototype.getVolume = function () {
  34089. return this._volume;
  34090. };
  34091. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34092. var _this = this;
  34093. this._connectedMesh = meshToConnectTo;
  34094. if (!this.spatialSound) {
  34095. this.spatialSound = true;
  34096. this._createSpatialParameters();
  34097. if (this.isPlaying && this.loop) {
  34098. this.stop();
  34099. this.play();
  34100. }
  34101. }
  34102. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34103. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34104. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34105. };
  34106. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34107. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34108. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34109. this._updateDirection();
  34110. }
  34111. };
  34112. Sound.Parse = function (parsedSound, scene, rootUrl) {
  34113. var soundName = parsedSound.name;
  34114. var soundUrl = rootUrl + soundName;
  34115. var options = {
  34116. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34117. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34118. rolloffFactor: parsedSound.rolloffFactor,
  34119. refDistance: parsedSound.refDistance,
  34120. distanceModel: parsedSound.distanceModel,
  34121. playbackRate: parsedSound.playbackRate
  34122. };
  34123. var newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34124. scene._addPendingData(newSound);
  34125. if (parsedSound.position) {
  34126. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34127. newSound.setPosition(soundPosition);
  34128. }
  34129. if (parsedSound.isDirectional) {
  34130. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34131. if (parsedSound.localDirectionToMesh) {
  34132. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34133. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34134. }
  34135. }
  34136. if (parsedSound.connectedMeshId) {
  34137. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34138. if (connectedMesh) {
  34139. newSound.attachToMesh(connectedMesh);
  34140. }
  34141. }
  34142. return newSound;
  34143. };
  34144. return Sound;
  34145. })();
  34146. BABYLON.Sound = Sound;
  34147. })(BABYLON || (BABYLON = {}));
  34148. var BABYLON;
  34149. (function (BABYLON) {
  34150. var SoundTrack = (function () {
  34151. function SoundTrack(scene, options) {
  34152. this.id = -1;
  34153. this._isMainTrack = false;
  34154. this._isInitialized = false;
  34155. this._scene = scene;
  34156. this.soundCollection = new Array();
  34157. this._options = options;
  34158. if (!this._isMainTrack) {
  34159. this._scene.soundTracks.push(this);
  34160. this.id = this._scene.soundTracks.length - 1;
  34161. }
  34162. }
  34163. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34164. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34165. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34166. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34167. if (this._options) {
  34168. if (this._options.volume) {
  34169. this._outputAudioNode.gain.value = this._options.volume;
  34170. }
  34171. if (this._options.mainTrack) {
  34172. this._isMainTrack = this._options.mainTrack;
  34173. }
  34174. }
  34175. this._isInitialized = true;
  34176. }
  34177. };
  34178. SoundTrack.prototype.dispose = function () {
  34179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34180. if (this._connectedAnalyser) {
  34181. this._connectedAnalyser.stopDebugCanvas();
  34182. }
  34183. while (this.soundCollection.length) {
  34184. this.soundCollection[0].dispose();
  34185. }
  34186. if (this._outputAudioNode) {
  34187. this._outputAudioNode.disconnect();
  34188. }
  34189. this._outputAudioNode = null;
  34190. }
  34191. };
  34192. SoundTrack.prototype.AddSound = function (sound) {
  34193. if (!this._isInitialized) {
  34194. this._initializeSoundTrackAudioGraph();
  34195. }
  34196. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34197. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34198. }
  34199. if (sound.soundTrackId) {
  34200. if (sound.soundTrackId === -1) {
  34201. this._scene.mainSoundTrack.RemoveSound(sound);
  34202. }
  34203. else {
  34204. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34205. }
  34206. }
  34207. this.soundCollection.push(sound);
  34208. sound.soundTrackId = this.id;
  34209. };
  34210. SoundTrack.prototype.RemoveSound = function (sound) {
  34211. var index = this.soundCollection.indexOf(sound);
  34212. if (index !== -1) {
  34213. this.soundCollection.splice(index, 1);
  34214. }
  34215. };
  34216. SoundTrack.prototype.setVolume = function (newVolume) {
  34217. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34218. this._outputAudioNode.gain.value = newVolume;
  34219. }
  34220. };
  34221. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34222. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34223. for (var i = 0; i < this.soundCollection.length; i++) {
  34224. this.soundCollection[i].switchPanningModelToHRTF();
  34225. }
  34226. }
  34227. };
  34228. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34230. for (var i = 0; i < this.soundCollection.length; i++) {
  34231. this.soundCollection[i].switchPanningModelToEqualPower();
  34232. }
  34233. }
  34234. };
  34235. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34236. if (this._connectedAnalyser) {
  34237. this._connectedAnalyser.stopDebugCanvas();
  34238. }
  34239. this._connectedAnalyser = analyser;
  34240. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34241. this._outputAudioNode.disconnect();
  34242. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34243. }
  34244. };
  34245. return SoundTrack;
  34246. })();
  34247. BABYLON.SoundTrack = SoundTrack;
  34248. })(BABYLON || (BABYLON = {}));
  34249. var BABYLON;
  34250. (function (BABYLON) {
  34251. var DepthRenderer = (function () {
  34252. function DepthRenderer(scene, type) {
  34253. var _this = this;
  34254. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34255. this._viewMatrix = BABYLON.Matrix.Zero();
  34256. this._projectionMatrix = BABYLON.Matrix.Zero();
  34257. this._transformMatrix = BABYLON.Matrix.Zero();
  34258. this._worldViewProjection = BABYLON.Matrix.Zero();
  34259. this._scene = scene;
  34260. var engine = scene.getEngine();
  34261. // Render target
  34262. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34263. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34264. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34265. this._depthMap.refreshRate = 1;
  34266. this._depthMap.renderParticles = false;
  34267. this._depthMap.renderList = null;
  34268. // set default depth value to 1.0 (far away)
  34269. this._depthMap.onClear = function (engine) {
  34270. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34271. };
  34272. // Custom render function
  34273. var renderSubMesh = function (subMesh) {
  34274. var mesh = subMesh.getRenderingMesh();
  34275. var scene = _this._scene;
  34276. var engine = scene.getEngine();
  34277. // Culling
  34278. engine.setState(subMesh.getMaterial().backFaceCulling);
  34279. // Managing instances
  34280. var batch = mesh._getInstancesRenderList(subMesh._id);
  34281. if (batch.mustReturn) {
  34282. return;
  34283. }
  34284. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34285. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34286. engine.enableEffect(_this._effect);
  34287. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34288. var material = subMesh.getMaterial();
  34289. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34290. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34291. // Alpha test
  34292. if (material && material.needAlphaTesting()) {
  34293. var alphaTexture = material.getAlphaTestTexture();
  34294. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34295. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34296. }
  34297. // Bones
  34298. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34299. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34300. }
  34301. // Draw
  34302. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34303. }
  34304. };
  34305. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34306. var index;
  34307. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34308. renderSubMesh(opaqueSubMeshes.data[index]);
  34309. }
  34310. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34311. renderSubMesh(alphaTestSubMeshes.data[index]);
  34312. }
  34313. };
  34314. }
  34315. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34316. var defines = [];
  34317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34318. var mesh = subMesh.getMesh();
  34319. var scene = mesh.getScene();
  34320. var material = subMesh.getMaterial();
  34321. // Alpha test
  34322. if (material && material.needAlphaTesting()) {
  34323. defines.push("#define ALPHATEST");
  34324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34325. attribs.push(BABYLON.VertexBuffer.UVKind);
  34326. defines.push("#define UV1");
  34327. }
  34328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34330. defines.push("#define UV2");
  34331. }
  34332. }
  34333. // Bones
  34334. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34337. if (mesh.numBoneInfluencers > 4) {
  34338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34340. }
  34341. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34342. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34343. }
  34344. else {
  34345. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34346. }
  34347. // Instances
  34348. if (useInstances) {
  34349. defines.push("#define INSTANCES");
  34350. attribs.push("world0");
  34351. attribs.push("world1");
  34352. attribs.push("world2");
  34353. attribs.push("world3");
  34354. }
  34355. // Get correct effect
  34356. var join = defines.join("\n");
  34357. if (this._cachedDefines !== join) {
  34358. this._cachedDefines = join;
  34359. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34360. }
  34361. return this._effect.isReady();
  34362. };
  34363. DepthRenderer.prototype.getDepthMap = function () {
  34364. return this._depthMap;
  34365. };
  34366. // Methods
  34367. DepthRenderer.prototype.dispose = function () {
  34368. this._depthMap.dispose();
  34369. };
  34370. return DepthRenderer;
  34371. })();
  34372. BABYLON.DepthRenderer = DepthRenderer;
  34373. })(BABYLON || (BABYLON = {}));
  34374. var BABYLON;
  34375. (function (BABYLON) {
  34376. var SSAORenderingPipeline = (function (_super) {
  34377. __extends(SSAORenderingPipeline, _super);
  34378. /**
  34379. * @constructor
  34380. * @param {string} name - The rendering pipeline name
  34381. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34382. * @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 }
  34383. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34384. */
  34385. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34386. var _this = this;
  34387. _super.call(this, scene.getEngine(), name);
  34388. // Members
  34389. /**
  34390. * The PassPostProcess id in the pipeline that contains the original scene color
  34391. * @type {string}
  34392. */
  34393. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34394. /**
  34395. * The SSAO PostProcess id in the pipeline
  34396. * @type {string}
  34397. */
  34398. this.SSAORenderEffect = "SSAORenderEffect";
  34399. /**
  34400. * The horizontal blur PostProcess id in the pipeline
  34401. * @type {string}
  34402. */
  34403. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34404. /**
  34405. * The vertical blur PostProcess id in the pipeline
  34406. * @type {string}
  34407. */
  34408. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34409. /**
  34410. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34411. * @type {string}
  34412. */
  34413. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34414. /**
  34415. * The output strength of the SSAO post-process. Default value is 1.0.
  34416. * @type {number}
  34417. */
  34418. this.totalStrength = 1.0;
  34419. /**
  34420. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34421. * @type {number}
  34422. */
  34423. this.radius = 0.0001;
  34424. /**
  34425. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34426. * Must not be equal to fallOff and superior to fallOff.
  34427. * Default value is 0.975
  34428. * @type {number}
  34429. */
  34430. this.area = 0.0075;
  34431. /**
  34432. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34433. * Must not be equal to area and inferior to area.
  34434. * Default value is 0.0
  34435. * @type {number}
  34436. */
  34437. this.fallOff = 0.000001;
  34438. /**
  34439. * The base color of the SSAO post-process
  34440. * The final result is "base + ssao" between [0, 1]
  34441. * @type {number}
  34442. */
  34443. this.base = 0.5;
  34444. this._firstUpdate = true;
  34445. this._scene = scene;
  34446. // Set up assets
  34447. this._createRandomTexture();
  34448. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34449. var ssaoRatio = ratio.ssaoRatio || ratio;
  34450. var combineRatio = ratio.combineRatio || ratio;
  34451. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34452. this._createSSAOPostProcess(ssaoRatio);
  34453. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34454. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34455. this._createSSAOCombinePostProcess(combineRatio);
  34456. // Set up pipeline
  34457. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34462. // Finish
  34463. scene.postProcessRenderPipelineManager.addPipeline(this);
  34464. if (cameras)
  34465. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34466. }
  34467. // Public Methods
  34468. /**
  34469. * Returns the horizontal blur PostProcess
  34470. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34471. */
  34472. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34473. return this._blurHPostProcess;
  34474. };
  34475. /**
  34476. * Returns the vertical blur PostProcess
  34477. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34478. */
  34479. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34480. return this._blurVPostProcess;
  34481. };
  34482. /**
  34483. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34484. */
  34485. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34486. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34487. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34488. this._originalColorPostProcess = undefined;
  34489. this._ssaoPostProcess = undefined;
  34490. this._blurHPostProcess = undefined;
  34491. this._blurVPostProcess = undefined;
  34492. this._ssaoCombinePostProcess = undefined;
  34493. this._randomTexture.dispose();
  34494. if (disableDepthRender)
  34495. this._scene.disableDepthRenderer();
  34496. };
  34497. // Private Methods
  34498. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34499. var _this = this;
  34500. var numSamples = 16;
  34501. var sampleSphere = [
  34502. 0.5381, 0.1856, -0.4319,
  34503. 0.1379, 0.2486, 0.4430,
  34504. 0.3371, 0.5679, -0.0057,
  34505. -0.6999, -0.0451, -0.0019,
  34506. 0.0689, -0.1598, -0.8547,
  34507. 0.0560, 0.0069, -0.1843,
  34508. -0.0146, 0.1402, 0.0762,
  34509. 0.0100, -0.1924, -0.0344,
  34510. -0.3577, -0.5301, -0.4358,
  34511. -0.3169, 0.1063, 0.0158,
  34512. 0.0103, -0.5869, 0.0046,
  34513. -0.0897, -0.4940, 0.3287,
  34514. 0.7119, -0.0154, -0.0918,
  34515. -0.0533, 0.0596, -0.5411,
  34516. 0.0352, -0.0631, 0.5460,
  34517. -0.4776, 0.2847, -0.0271
  34518. ];
  34519. var samplesFactor = 1.0 / numSamples;
  34520. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34521. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34522. "area", "fallOff", "base"
  34523. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34524. this._ssaoPostProcess.onApply = function (effect) {
  34525. if (_this._firstUpdate) {
  34526. effect.setArray3("sampleSphere", sampleSphere);
  34527. effect.setFloat("samplesFactor", samplesFactor);
  34528. effect.setFloat("randTextureTiles", 4.0);
  34529. _this._firstUpdate = false;
  34530. }
  34531. effect.setFloat("totalStrength", _this.totalStrength);
  34532. effect.setFloat("radius", _this.radius);
  34533. effect.setFloat("area", _this.area);
  34534. effect.setFloat("fallOff", _this.fallOff);
  34535. effect.setFloat("base", _this.base);
  34536. effect.setTexture("textureSampler", _this._depthTexture);
  34537. effect.setTexture("randomSampler", _this._randomTexture);
  34538. };
  34539. };
  34540. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34541. var _this = this;
  34542. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34543. this._ssaoCombinePostProcess.onApply = function (effect) {
  34544. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34545. };
  34546. };
  34547. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34548. var size = 512;
  34549. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34550. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34551. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34552. var context = this._randomTexture.getContext();
  34553. var rand = function (min, max) {
  34554. return Math.random() * (max - min) + min;
  34555. };
  34556. var randVector = BABYLON.Vector3.Zero();
  34557. for (var x = 0; x < size; x++) {
  34558. for (var y = 0; y < size; y++) {
  34559. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34560. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34561. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34562. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34563. context.fillRect(x, y, 1, 1);
  34564. }
  34565. }
  34566. this._randomTexture.update(false);
  34567. };
  34568. return SSAORenderingPipeline;
  34569. })(BABYLON.PostProcessRenderPipeline);
  34570. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34571. })(BABYLON || (BABYLON = {}));
  34572. var BABYLON;
  34573. (function (BABYLON) {
  34574. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34575. var VolumetricLightScatteringPostProcess = (function (_super) {
  34576. __extends(VolumetricLightScatteringPostProcess, _super);
  34577. /**
  34578. * @constructor
  34579. * @param {string} name - The post-process name
  34580. * @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)
  34581. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34582. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34583. * @param {number} samples - The post-process quality, default 100
  34584. * @param {number} samplingMode - The post-process filtering mode
  34585. * @param {BABYLON.Engine} engine - The babylon engine
  34586. * @param {boolean} reusable - If the post-process is reusable
  34587. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34588. */
  34589. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34590. var _this = this;
  34591. if (samples === void 0) { samples = 100; }
  34592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34593. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34594. this._screenCoordinates = BABYLON.Vector2.Zero();
  34595. /**
  34596. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34597. * @type {boolean}
  34598. */
  34599. this.useCustomMeshPosition = false;
  34600. /**
  34601. * If the post-process should inverse the light scattering direction
  34602. * @type {boolean}
  34603. */
  34604. this.invert = true;
  34605. /**
  34606. * Set to true to use the diffuseColor instead of the diffuseTexture
  34607. * @type {boolean}
  34608. */
  34609. this.useDiffuseColor = false;
  34610. /**
  34611. * Array containing the excluded meshes not rendered in the internal pass
  34612. */
  34613. this.excludedMeshes = new Array();
  34614. /**
  34615. * Controls the overall intensity of the post-process
  34616. * @type {number}
  34617. */
  34618. this.exposure = 0.3;
  34619. /**
  34620. * Dissipates each sample's contribution in range [0, 1]
  34621. * @type {number}
  34622. */
  34623. this.decay = 0.96815;
  34624. /**
  34625. * Controls the overall intensity of each sample
  34626. * @type {number}
  34627. */
  34628. this.weight = 0.58767;
  34629. /**
  34630. * Controls the density of each sample
  34631. * @type {number}
  34632. */
  34633. this.density = 0.926;
  34634. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34635. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34636. // Configure mesh
  34637. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34638. // Configure
  34639. this._createPass(scene, ratio.passRatio || ratio);
  34640. this.onActivate = function (camera) {
  34641. if (!_this.isSupported) {
  34642. _this.dispose(camera);
  34643. }
  34644. _this.onActivate = null;
  34645. };
  34646. this.onApply = function (effect) {
  34647. _this._updateMeshScreenCoordinates(scene);
  34648. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34649. effect.setFloat("exposure", _this.exposure);
  34650. effect.setFloat("decay", _this.decay);
  34651. effect.setFloat("weight", _this.weight);
  34652. effect.setFloat("density", _this.density);
  34653. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34654. };
  34655. }
  34656. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34657. var mesh = subMesh.getMesh();
  34658. var defines = [];
  34659. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34660. var material = subMesh.getMaterial();
  34661. var needUV = false;
  34662. // Render this.mesh as default
  34663. if (mesh === this.mesh) {
  34664. if (this.useDiffuseColor) {
  34665. defines.push("#define DIFFUSE_COLOR_RENDER");
  34666. }
  34667. else if (material) {
  34668. if (material.diffuseTexture !== undefined) {
  34669. defines.push("#define BASIC_RENDER");
  34670. }
  34671. else {
  34672. defines.push("#define DIFFUSE_COLOR_RENDER");
  34673. }
  34674. }
  34675. defines.push("#define NEED_UV");
  34676. needUV = true;
  34677. }
  34678. // Alpha test
  34679. if (material) {
  34680. if (material.needAlphaTesting()) {
  34681. defines.push("#define ALPHATEST");
  34682. }
  34683. if (material.opacityTexture !== undefined) {
  34684. defines.push("#define OPACITY");
  34685. if (material.opacityTexture.getAlphaFromRGB) {
  34686. defines.push("#define OPACITYRGB");
  34687. }
  34688. if (!needUV) {
  34689. defines.push("#define NEED_UV");
  34690. }
  34691. }
  34692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34693. attribs.push(BABYLON.VertexBuffer.UVKind);
  34694. defines.push("#define UV1");
  34695. }
  34696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34697. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34698. defines.push("#define UV2");
  34699. }
  34700. }
  34701. // Bones
  34702. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34705. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34706. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34707. }
  34708. else {
  34709. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34710. }
  34711. // Instances
  34712. if (useInstances) {
  34713. defines.push("#define INSTANCES");
  34714. attribs.push("world0");
  34715. attribs.push("world1");
  34716. attribs.push("world2");
  34717. attribs.push("world3");
  34718. }
  34719. // Get correct effect
  34720. var join = defines.join("\n");
  34721. if (this._cachedDefines !== join) {
  34722. this._cachedDefines = join;
  34723. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34724. }
  34725. return this._volumetricLightScatteringPass.isReady();
  34726. };
  34727. /**
  34728. * Sets the new light position for light scattering effect
  34729. * @param {BABYLON.Vector3} The new custom light position
  34730. */
  34731. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34732. this._customMeshPosition = position;
  34733. };
  34734. /**
  34735. * Returns the light position for light scattering effect
  34736. * @return {BABYLON.Vector3} The custom light position
  34737. */
  34738. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34739. return this._customMeshPosition;
  34740. };
  34741. /**
  34742. * Disposes the internal assets and detaches the post-process from the camera
  34743. */
  34744. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34745. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34746. if (rttIndex !== -1) {
  34747. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34748. }
  34749. this._volumetricLightScatteringRTT.dispose();
  34750. _super.prototype.dispose.call(this, camera);
  34751. };
  34752. /**
  34753. * Returns the render target texture used by the post-process
  34754. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34755. */
  34756. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34757. return this._volumetricLightScatteringRTT;
  34758. };
  34759. // Private methods
  34760. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34761. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34762. return true;
  34763. }
  34764. return false;
  34765. };
  34766. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34767. var _this = this;
  34768. var engine = scene.getEngine();
  34769. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34770. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34771. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34772. this._volumetricLightScatteringRTT.renderList = null;
  34773. this._volumetricLightScatteringRTT.renderParticles = false;
  34774. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34775. // Custom render function for submeshes
  34776. var renderSubMesh = function (subMesh) {
  34777. var mesh = subMesh.getRenderingMesh();
  34778. if (_this._meshExcluded(mesh)) {
  34779. return;
  34780. }
  34781. var scene = mesh.getScene();
  34782. var engine = scene.getEngine();
  34783. // Culling
  34784. engine.setState(subMesh.getMaterial().backFaceCulling);
  34785. // Managing instances
  34786. var batch = mesh._getInstancesRenderList(subMesh._id);
  34787. if (batch.mustReturn) {
  34788. return;
  34789. }
  34790. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34791. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34792. engine.enableEffect(_this._volumetricLightScatteringPass);
  34793. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34794. var material = subMesh.getMaterial();
  34795. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34796. // Alpha test
  34797. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34798. var alphaTexture = material.getAlphaTestTexture();
  34799. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34800. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34801. }
  34802. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34803. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34804. if (alphaTexture) {
  34805. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34806. }
  34807. }
  34808. if (material.opacityTexture !== undefined) {
  34809. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34810. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34811. }
  34812. }
  34813. // Bones
  34814. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34815. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34816. }
  34817. // Draw
  34818. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34819. }
  34820. };
  34821. // Render target texture callbacks
  34822. var savedSceneClearColor;
  34823. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34824. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34825. savedSceneClearColor = scene.clearColor;
  34826. scene.clearColor = sceneClearColor;
  34827. };
  34828. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34829. scene.clearColor = savedSceneClearColor;
  34830. };
  34831. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34832. var engine = scene.getEngine();
  34833. var index;
  34834. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34835. renderSubMesh(opaqueSubMeshes.data[index]);
  34836. }
  34837. engine.setAlphaTesting(true);
  34838. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34839. renderSubMesh(alphaTestSubMeshes.data[index]);
  34840. }
  34841. engine.setAlphaTesting(false);
  34842. if (transparentSubMeshes.length) {
  34843. // Sort sub meshes
  34844. for (index = 0; index < transparentSubMeshes.length; index++) {
  34845. var submesh = transparentSubMeshes.data[index];
  34846. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34847. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34848. }
  34849. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34850. sortedArray.sort(function (a, b) {
  34851. // Alpha index first
  34852. if (a._alphaIndex > b._alphaIndex) {
  34853. return 1;
  34854. }
  34855. if (a._alphaIndex < b._alphaIndex) {
  34856. return -1;
  34857. }
  34858. // Then distance to camera
  34859. if (a._distanceToCamera < b._distanceToCamera) {
  34860. return 1;
  34861. }
  34862. if (a._distanceToCamera > b._distanceToCamera) {
  34863. return -1;
  34864. }
  34865. return 0;
  34866. });
  34867. // Render sub meshes
  34868. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34869. for (index = 0; index < sortedArray.length; index++) {
  34870. renderSubMesh(sortedArray[index]);
  34871. }
  34872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34873. }
  34874. };
  34875. };
  34876. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34877. var transform = scene.getTransformMatrix();
  34878. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34879. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34880. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34881. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34882. if (this.invert)
  34883. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34884. };
  34885. // Static methods
  34886. /**
  34887. * Creates a default mesh for the Volumeric Light Scattering post-process
  34888. * @param {string} The mesh name
  34889. * @param {BABYLON.Scene} The scene where to create the mesh
  34890. * @return {BABYLON.Mesh} the default mesh
  34891. */
  34892. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34893. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34894. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34895. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34896. return mesh;
  34897. };
  34898. return VolumetricLightScatteringPostProcess;
  34899. })(BABYLON.PostProcess);
  34900. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34901. })(BABYLON || (BABYLON = {}));
  34902. // BABYLON.JS Chromatic Aberration GLSL Shader
  34903. // Author: Olivier Guyot
  34904. // Separates very slightly R, G and B colors on the edges of the screen
  34905. // Inspired by Francois Tarlier & Martins Upitis
  34906. var BABYLON;
  34907. (function (BABYLON) {
  34908. var LensRenderingPipeline = (function (_super) {
  34909. __extends(LensRenderingPipeline, _super);
  34910. /**
  34911. * @constructor
  34912. *
  34913. * Effect parameters are as follow:
  34914. * {
  34915. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34916. * edge_blur: number; // from 0 to x (1 for realism)
  34917. * distortion: number; // from 0 to x (1 for realism)
  34918. * grain_amount: number; // from 0 to 1
  34919. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34920. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34921. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34922. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34923. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34924. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34925. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34926. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34927. * }
  34928. * Note: if an effect parameter is unset, effect is disabled
  34929. *
  34930. * @param {string} name - The rendering pipeline name
  34931. * @param {object} parameters - An object containing all parameters (see above)
  34932. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34933. * @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)
  34934. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34935. */
  34936. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34937. var _this = this;
  34938. if (ratio === void 0) { ratio = 1.0; }
  34939. _super.call(this, scene.getEngine(), name);
  34940. // Lens effects can be of the following:
  34941. // - chromatic aberration (slight shift of RGB colors)
  34942. // - blur on the edge of the lens
  34943. // - lens distortion
  34944. // - depth-of-field blur & highlights enhancing
  34945. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34946. // - grain effect (noise or custom texture)
  34947. // Two additional texture samplers are needed:
  34948. // - depth map (for depth-of-field)
  34949. // - grain texture
  34950. /**
  34951. * The chromatic aberration PostProcess id in the pipeline
  34952. * @type {string}
  34953. */
  34954. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34955. /**
  34956. * The highlights enhancing PostProcess id in the pipeline
  34957. * @type {string}
  34958. */
  34959. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34960. /**
  34961. * The depth-of-field PostProcess id in the pipeline
  34962. * @type {string}
  34963. */
  34964. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34965. this._scene = scene;
  34966. // Fetch texture samplers
  34967. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34968. if (parameters.grain_texture) {
  34969. this._grainTexture = parameters.grain_texture;
  34970. }
  34971. else {
  34972. this._createGrainTexture();
  34973. }
  34974. // save parameters
  34975. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34976. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34977. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34978. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34979. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34980. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34981. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34982. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34983. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34984. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34985. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34986. // Create effects
  34987. this._createChromaticAberrationPostProcess(ratio);
  34988. this._createHighlightsPostProcess(ratio);
  34989. this._createDepthOfFieldPostProcess(ratio / 4);
  34990. // Set up pipeline
  34991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34994. if (this._highlightsGain === -1) {
  34995. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34996. }
  34997. // Finish
  34998. scene.postProcessRenderPipelineManager.addPipeline(this);
  34999. if (cameras) {
  35000. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35001. }
  35002. }
  35003. // public methods (self explanatory)
  35004. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35005. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35006. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35007. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35008. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35009. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35010. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35011. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35012. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35013. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35014. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35015. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35016. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35017. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35018. };
  35019. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35020. this._highlightsPostProcess.updateEffect();
  35021. };
  35022. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35023. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35024. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35025. this._highlightsGain = amount;
  35026. };
  35027. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35028. if (this._highlightsGain === -1) {
  35029. this._highlightsGain = 1.0;
  35030. }
  35031. this._highlightsThreshold = amount;
  35032. };
  35033. LensRenderingPipeline.prototype.disableHighlights = function () {
  35034. this._highlightsGain = -1;
  35035. };
  35036. /**
  35037. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35038. */
  35039. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35040. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35041. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35042. this._chromaticAberrationPostProcess = undefined;
  35043. this._highlightsPostProcess = undefined;
  35044. this._depthOfFieldPostProcess = undefined;
  35045. this._grainTexture.dispose();
  35046. if (disableDepthRender)
  35047. this._scene.disableDepthRenderer();
  35048. };
  35049. // colors shifting and distortion
  35050. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35051. var _this = this;
  35052. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35053. [], // samplers
  35054. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35055. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35056. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35059. };
  35060. };
  35061. // highlights enhancing
  35062. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35063. var _this = this;
  35064. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35065. [], // samplers
  35066. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35067. this._highlightsPostProcess.onApply = function (effect) {
  35068. effect.setFloat('gain', _this._highlightsGain);
  35069. effect.setFloat('threshold', _this._highlightsThreshold);
  35070. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35071. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35072. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35073. };
  35074. };
  35075. // colors shifting and distortion
  35076. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35077. var _this = this;
  35078. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35079. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35080. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35081. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35082. this._depthOfFieldPostProcess.onApply = function (effect) {
  35083. effect.setTexture("depthSampler", _this._depthTexture);
  35084. effect.setTexture("grainSampler", _this._grainTexture);
  35085. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35086. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35087. effect.setFloat('grain_amount', _this._grainAmount);
  35088. effect.setBool('blur_noise', _this._blurNoise);
  35089. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35090. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35091. effect.setFloat('distortion', _this._distortion);
  35092. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35093. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35094. effect.setFloat('aperture', _this._dofAperture);
  35095. effect.setFloat('darken', _this._dofDarken);
  35096. effect.setFloat('edge_blur', _this._edgeBlur);
  35097. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35098. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35099. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35100. };
  35101. };
  35102. // creates a black and white random noise texture, 512x512
  35103. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35104. var size = 512;
  35105. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35106. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35107. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35108. var context = this._grainTexture.getContext();
  35109. var rand = function (min, max) {
  35110. return Math.random() * (max - min) + min;
  35111. };
  35112. var value;
  35113. for (var x = 0; x < size; x++) {
  35114. for (var y = 0; y < size; y++) {
  35115. value = Math.floor(rand(0.42, 0.58) * 255);
  35116. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35117. context.fillRect(x, y, 1, 1);
  35118. }
  35119. }
  35120. this._grainTexture.update(false);
  35121. };
  35122. return LensRenderingPipeline;
  35123. })(BABYLON.PostProcessRenderPipeline);
  35124. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35125. })(BABYLON || (BABYLON = {}));
  35126. //
  35127. // This post-process allows the modification of rendered colors by using
  35128. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35129. //
  35130. // The object needs to be provided an url to a texture containing the color
  35131. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35132. // Use an image editing software to tweak the LUT to match your needs.
  35133. //
  35134. // For an example of a color LUT, see here:
  35135. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35136. // For explanations on color grading, see here:
  35137. // http://udn.epicgames.com/Three/ColorGrading.html
  35138. //
  35139. var BABYLON;
  35140. (function (BABYLON) {
  35141. var ColorCorrectionPostProcess = (function (_super) {
  35142. __extends(ColorCorrectionPostProcess, _super);
  35143. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35144. var _this = this;
  35145. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35146. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35147. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35148. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35149. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35150. this.onApply = function (effect) {
  35151. effect.setTexture("colorTable", _this._colorTableTexture);
  35152. };
  35153. }
  35154. return ColorCorrectionPostProcess;
  35155. })(BABYLON.PostProcess);
  35156. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35157. })(BABYLON || (BABYLON = {}));
  35158. var BABYLON;
  35159. (function (BABYLON) {
  35160. var AnaglyphFreeCamera = (function (_super) {
  35161. __extends(AnaglyphFreeCamera, _super);
  35162. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35163. _super.call(this, name, position, scene);
  35164. this.interaxialDistance = interaxialDistance;
  35165. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35166. }
  35167. return AnaglyphFreeCamera;
  35168. })(BABYLON.FreeCamera);
  35169. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35170. var AnaglyphArcRotateCamera = (function (_super) {
  35171. __extends(AnaglyphArcRotateCamera, _super);
  35172. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35173. _super.call(this, name, alpha, beta, radius, target, scene);
  35174. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35175. }
  35176. return AnaglyphArcRotateCamera;
  35177. })(BABYLON.ArcRotateCamera);
  35178. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35179. var AnaglyphGamepadCamera = (function (_super) {
  35180. __extends(AnaglyphGamepadCamera, _super);
  35181. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35182. _super.call(this, name, position, scene);
  35183. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35184. }
  35185. return AnaglyphGamepadCamera;
  35186. })(BABYLON.GamepadCamera);
  35187. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35188. var StereoscopicFreeCamera = (function (_super) {
  35189. __extends(StereoscopicFreeCamera, _super);
  35190. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35191. _super.call(this, name, position, scene);
  35192. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35193. }
  35194. return StereoscopicFreeCamera;
  35195. })(BABYLON.FreeCamera);
  35196. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35197. var StereoscopicArcRotateCamera = (function (_super) {
  35198. __extends(StereoscopicArcRotateCamera, _super);
  35199. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35200. _super.call(this, name, alpha, beta, radius, target, scene);
  35201. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35202. }
  35203. return StereoscopicArcRotateCamera;
  35204. })(BABYLON.ArcRotateCamera);
  35205. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35206. var StereoscopicGamepadCamera = (function (_super) {
  35207. __extends(StereoscopicGamepadCamera, _super);
  35208. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35209. _super.call(this, name, position, scene);
  35210. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35211. }
  35212. return StereoscopicGamepadCamera;
  35213. })(BABYLON.GamepadCamera);
  35214. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35215. })(BABYLON || (BABYLON = {}));
  35216. var BABYLON;
  35217. (function (BABYLON) {
  35218. var HDRRenderingPipeline = (function (_super) {
  35219. __extends(HDRRenderingPipeline, _super);
  35220. /**
  35221. * @constructor
  35222. * @param {string} name - The rendering pipeline name
  35223. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35224. * @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)
  35225. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35226. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35227. */
  35228. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35229. var _this = this;
  35230. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35231. _super.call(this, scene.getEngine(), name);
  35232. /**
  35233. * Public members
  35234. */
  35235. // Gaussian Blur
  35236. /**
  35237. * Gaussian blur coefficient
  35238. * @type {number}
  35239. */
  35240. this.gaussCoeff = 0.3;
  35241. /**
  35242. * Gaussian blur mean
  35243. * @type {number}
  35244. */
  35245. this.gaussMean = 1.0;
  35246. /**
  35247. * Gaussian blur standard deviation
  35248. * @type {number}
  35249. */
  35250. this.gaussStandDev = 0.8;
  35251. /**
  35252. * Gaussian blur multiplier. Multiplies the blur effect
  35253. * @type {number}
  35254. */
  35255. this.gaussMultiplier = 4.0;
  35256. // HDR
  35257. /**
  35258. * Exposure, controls the overall intensity of the pipeline
  35259. * @type {number}
  35260. */
  35261. this.exposure = 1.0;
  35262. /**
  35263. * Minimum luminance that the post-process can output. Luminance is >= 0
  35264. * @type {number}
  35265. */
  35266. this.minimumLuminance = 1.0;
  35267. /**
  35268. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35269. * @type {number}
  35270. */
  35271. this.maximumLuminance = 1e20;
  35272. /**
  35273. * Increase rate for luminance: eye adaptation speed to dark
  35274. * @type {number}
  35275. */
  35276. this.luminanceIncreaserate = 0.5;
  35277. /**
  35278. * Decrease rate for luminance: eye adaptation speed to bright
  35279. * @type {number}
  35280. */
  35281. this.luminanceDecreaseRate = 0.5;
  35282. // Bright pass
  35283. /**
  35284. * Minimum luminance needed to compute HDR
  35285. * @type {number}
  35286. */
  35287. this.brightThreshold = 0.8;
  35288. this._needUpdate = true;
  35289. this._scene = scene;
  35290. // Bright pass
  35291. this._createBrightPassPostProcess(scene, ratio);
  35292. // Down sample X4
  35293. this._createDownSampleX4PostProcess(scene, ratio);
  35294. // Create gaussian blur post-processes
  35295. this._createGaussianBlurPostProcess(scene, ratio);
  35296. // Texture adder
  35297. this._createTextureAdderPostProcess(scene, ratio);
  35298. // Luminance generator
  35299. this._createLuminanceGeneratorPostProcess(scene);
  35300. // HDR
  35301. this._createHDRPostProcess(scene, ratio);
  35302. // Pass postprocess
  35303. if (originalPostProcess === null) {
  35304. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35305. }
  35306. else {
  35307. this._originalPostProcess = originalPostProcess;
  35308. }
  35309. // Configure pipeline
  35310. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35311. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35315. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35316. var addDownSamplerPostProcess = function (id) {
  35317. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35318. };
  35319. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35320. addDownSamplerPostProcess(i);
  35321. }
  35322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35323. // Finish
  35324. scene.postProcessRenderPipelineManager.addPipeline(this);
  35325. if (cameras !== null) {
  35326. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35327. }
  35328. this.update();
  35329. }
  35330. /**
  35331. * Tells the pipeline to update its post-processes
  35332. */
  35333. HDRRenderingPipeline.prototype.update = function () {
  35334. this._needUpdate = true;
  35335. };
  35336. /**
  35337. * Returns the current calculated luminance
  35338. */
  35339. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35340. return this._hdrCurrentLuminance;
  35341. };
  35342. /**
  35343. * Returns the currently drawn luminance
  35344. */
  35345. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35346. return this._hdrOutputLuminance;
  35347. };
  35348. /**
  35349. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35350. */
  35351. HDRRenderingPipeline.prototype.dispose = function () {
  35352. this._originalPostProcess = undefined;
  35353. this._brightPassPostProcess = undefined;
  35354. this._downSampleX4PostProcess = undefined;
  35355. this._guassianBlurHPostProcess = undefined;
  35356. this._guassianBlurVPostProcess = undefined;
  35357. this._textureAdderPostProcess = undefined;
  35358. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35359. this._downSamplePostProcesses[i] = undefined;
  35360. }
  35361. this._hdrPostProcess = undefined;
  35362. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35363. };
  35364. /**
  35365. * Creates the HDR post-process and computes the luminance adaptation
  35366. */
  35367. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35368. var _this = this;
  35369. var hdrLastLuminance = 0.0;
  35370. this._hdrOutputLuminance = -1.0;
  35371. this._hdrCurrentLuminance = 1.0;
  35372. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35373. this._hdrPostProcess.onApply = function (effect) {
  35374. if (_this._hdrOutputLuminance < 0.0) {
  35375. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35376. }
  35377. else {
  35378. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35379. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35380. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35381. }
  35382. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35383. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35384. }
  35385. else {
  35386. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35387. }
  35388. }
  35389. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35390. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35391. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35392. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35393. effect.setFloat("exposure", _this.exposure);
  35394. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35395. _this._needUpdate = false;
  35396. };
  35397. };
  35398. /**
  35399. * Texture Adder post-process
  35400. */
  35401. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35402. var _this = this;
  35403. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35404. this._textureAdderPostProcess.onApply = function (effect) {
  35405. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35406. };
  35407. };
  35408. /**
  35409. * Down sample X4 post-process
  35410. */
  35411. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35412. var _this = this;
  35413. var downSampleX4Offsets = new Array(32);
  35414. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35415. this._downSampleX4PostProcess.onApply = function (effect) {
  35416. if (_this._needUpdate) {
  35417. var id = 0;
  35418. for (var i = -2; i < 2; i++) {
  35419. for (var j = -2; j < 2; j++) {
  35420. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35421. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35422. id += 2;
  35423. }
  35424. }
  35425. }
  35426. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35427. };
  35428. };
  35429. /**
  35430. * Bright pass post-process
  35431. */
  35432. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35433. var _this = this;
  35434. var brightOffsets = new Array(8);
  35435. var brightPassCallback = function (effect) {
  35436. if (_this._needUpdate) {
  35437. var sU = (1.0 / _this._brightPassPostProcess.width);
  35438. var sV = (1.0 / _this._brightPassPostProcess.height);
  35439. brightOffsets[0] = -0.5 * sU;
  35440. brightOffsets[1] = 0.5 * sV;
  35441. brightOffsets[2] = 0.5 * sU;
  35442. brightOffsets[3] = 0.5 * sV;
  35443. brightOffsets[4] = -0.5 * sU;
  35444. brightOffsets[5] = -0.5 * sV;
  35445. brightOffsets[6] = 0.5 * sU;
  35446. brightOffsets[7] = -0.5 * sV;
  35447. }
  35448. effect.setArray2("dsOffsets", brightOffsets);
  35449. effect.setFloat("brightThreshold", _this.brightThreshold);
  35450. };
  35451. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35452. this._brightPassPostProcess.onApply = brightPassCallback;
  35453. };
  35454. /**
  35455. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35456. */
  35457. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35458. var _this = this;
  35459. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35460. var luminanceOffsets = new Array(8);
  35461. var downSampleOffsets = new Array(18);
  35462. var halfDestPixelSize;
  35463. this._downSamplePostProcesses = new Array(lumSteps);
  35464. // Utils for luminance
  35465. var luminanceUpdateSourceOffsets = function (width, height) {
  35466. var sU = (1.0 / width);
  35467. var sV = (1.0 / height);
  35468. luminanceOffsets[0] = -0.5 * sU;
  35469. luminanceOffsets[1] = 0.5 * sV;
  35470. luminanceOffsets[2] = 0.5 * sU;
  35471. luminanceOffsets[3] = 0.5 * sV;
  35472. luminanceOffsets[4] = -0.5 * sU;
  35473. luminanceOffsets[5] = -0.5 * sV;
  35474. luminanceOffsets[6] = 0.5 * sU;
  35475. luminanceOffsets[7] = -0.5 * sV;
  35476. };
  35477. var luminanceUpdateDestOffsets = function (width, height) {
  35478. var id = 0;
  35479. for (var x = -1; x < 2; x++) {
  35480. for (var y = -1; y < 2; y++) {
  35481. downSampleOffsets[id] = (x) / width;
  35482. downSampleOffsets[id + 1] = (y) / height;
  35483. id += 2;
  35484. }
  35485. }
  35486. };
  35487. // Luminance callback
  35488. var luminanceCallback = function (effect) {
  35489. if (_this._needUpdate) {
  35490. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35491. }
  35492. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35493. effect.setArray2("lumOffsets", luminanceOffsets);
  35494. };
  35495. // Down sample callbacks
  35496. var downSampleCallback = function (indice) {
  35497. var i = indice;
  35498. return function (effect) {
  35499. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35500. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35501. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35502. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35503. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35504. effect.setArray2("dsOffsets", downSampleOffsets);
  35505. };
  35506. };
  35507. var downSampleAfterRenderCallback = function (effect) {
  35508. // Unpack result
  35509. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35510. 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);
  35511. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35512. };
  35513. // Create luminance post-process
  35514. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35515. 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);
  35516. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35517. // Create down sample post-processes
  35518. for (var i = lumSteps - 2; i >= 0; i--) {
  35519. var length = Math.pow(3, i);
  35520. ratio = { width: length, height: length };
  35521. var defines = "#define DOWN_SAMPLE\n";
  35522. if (i === 0) {
  35523. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35524. }
  35525. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35526. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35527. if (i === 0) {
  35528. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35529. }
  35530. }
  35531. };
  35532. /**
  35533. * Gaussian blur post-processes. Horizontal and Vertical
  35534. */
  35535. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35536. var _this = this;
  35537. var blurOffsetsW = new Array(9);
  35538. var blurOffsetsH = new Array(9);
  35539. var blurWeights = new Array(9);
  35540. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35541. // Utils for gaussian blur
  35542. var calculateBlurOffsets = function (height) {
  35543. var lastOutputDimensions = {
  35544. width: scene.getEngine().getRenderWidth(),
  35545. height: scene.getEngine().getRenderHeight()
  35546. };
  35547. for (var i = 0; i < 9; i++) {
  35548. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35549. if (height) {
  35550. blurOffsetsH[i] = value;
  35551. }
  35552. else {
  35553. blurOffsetsW[i] = value;
  35554. }
  35555. }
  35556. };
  35557. var calculateWeights = function () {
  35558. var x = 0.0;
  35559. for (var i = 0; i < 9; i++) {
  35560. x = (i - 4.0) / 4.0;
  35561. 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));
  35562. }
  35563. };
  35564. // Callback
  35565. var gaussianBlurCallback = function (height) {
  35566. return function (effect) {
  35567. if (_this._needUpdate) {
  35568. calculateWeights();
  35569. calculateBlurOffsets(height);
  35570. }
  35571. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35572. effect.setArray("blurWeights", blurWeights);
  35573. effect.setFloat("multiplier", _this.gaussMultiplier);
  35574. };
  35575. };
  35576. // Create horizontal gaussian blur post-processes
  35577. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35578. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35579. // Create vertical gaussian blur post-process
  35580. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35581. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35582. };
  35583. // Luminance generator
  35584. HDRRenderingPipeline.LUM_STEPS = 6;
  35585. return HDRRenderingPipeline;
  35586. })(BABYLON.PostProcessRenderPipeline);
  35587. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35588. })(BABYLON || (BABYLON = {}));
  35589. var BABYLON;
  35590. (function (BABYLON) {
  35591. var FaceAdjacencies = (function () {
  35592. function FaceAdjacencies() {
  35593. this.edges = new Array();
  35594. this.edgesConnectedCount = 0;
  35595. }
  35596. return FaceAdjacencies;
  35597. })();
  35598. var EdgesRenderer = (function () {
  35599. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35600. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35601. if (epsilon === void 0) { epsilon = 0.95; }
  35602. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35603. this._linesPositions = new Array();
  35604. this._linesNormals = new Array();
  35605. this._linesIndices = new Array();
  35606. this._buffers = new Array();
  35607. this._checkVerticesInsteadOfIndices = false;
  35608. this._source = source;
  35609. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35610. this._epsilon = epsilon;
  35611. this._prepareRessources();
  35612. this._generateEdgesLines();
  35613. }
  35614. EdgesRenderer.prototype._prepareRessources = function () {
  35615. if (this._lineShader) {
  35616. return;
  35617. }
  35618. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35619. attributes: ["position", "normal"],
  35620. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35621. });
  35622. this._lineShader.disableDepthWrite = true;
  35623. this._lineShader.backFaceCulling = false;
  35624. };
  35625. EdgesRenderer.prototype.dispose = function () {
  35626. this._vb0.dispose();
  35627. this._vb1.dispose();
  35628. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35629. this._lineShader.dispose();
  35630. };
  35631. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35632. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35633. return 0;
  35634. }
  35635. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35636. return 1;
  35637. }
  35638. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35639. return 2;
  35640. }
  35641. return -1;
  35642. };
  35643. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35644. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35645. return 0;
  35646. }
  35647. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35648. return 1;
  35649. }
  35650. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35651. return 2;
  35652. }
  35653. return -1;
  35654. };
  35655. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35656. var needToCreateLine;
  35657. if (edge === undefined) {
  35658. needToCreateLine = true;
  35659. }
  35660. else {
  35661. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35662. needToCreateLine = dotProduct < this._epsilon;
  35663. }
  35664. if (needToCreateLine) {
  35665. var offset = this._linesPositions.length / 3;
  35666. var normal = p0.subtract(p1);
  35667. normal.normalize();
  35668. // Positions
  35669. this._linesPositions.push(p0.x);
  35670. this._linesPositions.push(p0.y);
  35671. this._linesPositions.push(p0.z);
  35672. this._linesPositions.push(p0.x);
  35673. this._linesPositions.push(p0.y);
  35674. this._linesPositions.push(p0.z);
  35675. this._linesPositions.push(p1.x);
  35676. this._linesPositions.push(p1.y);
  35677. this._linesPositions.push(p1.z);
  35678. this._linesPositions.push(p1.x);
  35679. this._linesPositions.push(p1.y);
  35680. this._linesPositions.push(p1.z);
  35681. // Normals
  35682. this._linesNormals.push(p1.x);
  35683. this._linesNormals.push(p1.y);
  35684. this._linesNormals.push(p1.z);
  35685. this._linesNormals.push(-1);
  35686. this._linesNormals.push(p1.x);
  35687. this._linesNormals.push(p1.y);
  35688. this._linesNormals.push(p1.z);
  35689. this._linesNormals.push(1);
  35690. this._linesNormals.push(p0.x);
  35691. this._linesNormals.push(p0.y);
  35692. this._linesNormals.push(p0.z);
  35693. this._linesNormals.push(-1);
  35694. this._linesNormals.push(p0.x);
  35695. this._linesNormals.push(p0.y);
  35696. this._linesNormals.push(p0.z);
  35697. this._linesNormals.push(1);
  35698. // Indices
  35699. this._linesIndices.push(offset);
  35700. this._linesIndices.push(offset + 1);
  35701. this._linesIndices.push(offset + 2);
  35702. this._linesIndices.push(offset);
  35703. this._linesIndices.push(offset + 2);
  35704. this._linesIndices.push(offset + 3);
  35705. }
  35706. };
  35707. EdgesRenderer.prototype._generateEdgesLines = function () {
  35708. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35709. var indices = this._source.getIndices();
  35710. // First let's find adjacencies
  35711. var adjacencies = new Array();
  35712. var faceNormals = new Array();
  35713. var index;
  35714. var faceAdjacencies;
  35715. // Prepare faces
  35716. for (index = 0; index < indices.length; index += 3) {
  35717. faceAdjacencies = new FaceAdjacencies();
  35718. var p0Index = indices[index];
  35719. var p1Index = indices[index + 1];
  35720. var p2Index = indices[index + 2];
  35721. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35722. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35723. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35724. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35725. faceNormal.normalize();
  35726. faceNormals.push(faceNormal);
  35727. adjacencies.push(faceAdjacencies);
  35728. }
  35729. // Scan
  35730. for (index = 0; index < adjacencies.length; index++) {
  35731. faceAdjacencies = adjacencies[index];
  35732. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35733. var otherFaceAdjacencies = adjacencies[otherIndex];
  35734. if (faceAdjacencies.edgesConnectedCount === 3) {
  35735. break;
  35736. }
  35737. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35738. continue;
  35739. }
  35740. var otherP0 = indices[otherIndex * 3];
  35741. var otherP1 = indices[otherIndex * 3 + 1];
  35742. var otherP2 = indices[otherIndex * 3 + 2];
  35743. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35744. var otherEdgeIndex;
  35745. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35746. continue;
  35747. }
  35748. switch (edgeIndex) {
  35749. case 0:
  35750. if (this._checkVerticesInsteadOfIndices) {
  35751. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35752. }
  35753. else {
  35754. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35755. }
  35756. break;
  35757. case 1:
  35758. if (this._checkVerticesInsteadOfIndices) {
  35759. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35760. }
  35761. else {
  35762. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35763. }
  35764. break;
  35765. case 2:
  35766. if (this._checkVerticesInsteadOfIndices) {
  35767. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35768. }
  35769. else {
  35770. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35771. }
  35772. break;
  35773. }
  35774. if (otherEdgeIndex === -1) {
  35775. continue;
  35776. }
  35777. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35778. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35779. faceAdjacencies.edgesConnectedCount++;
  35780. otherFaceAdjacencies.edgesConnectedCount++;
  35781. if (faceAdjacencies.edgesConnectedCount === 3) {
  35782. break;
  35783. }
  35784. }
  35785. }
  35786. }
  35787. // Create lines
  35788. for (index = 0; index < adjacencies.length; index++) {
  35789. // 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
  35790. var current = adjacencies[index];
  35791. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35792. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35793. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35794. }
  35795. // Merge into a single mesh
  35796. var engine = this._source.getScene().getEngine();
  35797. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35798. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35799. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35800. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35801. this._ib = engine.createIndexBuffer(this._linesIndices);
  35802. this._indicesCount = this._linesIndices.length;
  35803. };
  35804. EdgesRenderer.prototype.render = function () {
  35805. if (!this._lineShader.isReady()) {
  35806. return;
  35807. }
  35808. var scene = this._source.getScene();
  35809. var engine = scene.getEngine();
  35810. this._lineShader._preBind();
  35811. // VBOs
  35812. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35813. scene.resetCachedMaterial();
  35814. this._lineShader.setColor4("color", this._source.edgesColor);
  35815. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35816. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35817. this._lineShader.bind(this._source.getWorldMatrix());
  35818. // Draw order
  35819. engine.draw(true, 0, this._indicesCount);
  35820. this._lineShader.unbind();
  35821. engine.setDepthWrite(true);
  35822. };
  35823. return EdgesRenderer;
  35824. })();
  35825. BABYLON.EdgesRenderer = EdgesRenderer;
  35826. })(BABYLON || (BABYLON = {}));
  35827. var BABYLON;
  35828. (function (BABYLON) {
  35829. (function (TonemappingOperator) {
  35830. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35831. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35832. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35833. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35834. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35835. var TonemappingOperator = BABYLON.TonemappingOperator;
  35836. ;
  35837. var TonemapPostProcess = (function (_super) {
  35838. __extends(TonemapPostProcess, _super);
  35839. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35840. var _this = this;
  35841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35842. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35843. this._operator = operator;
  35844. this._exposureAdjustment = exposureAdjustment;
  35845. var params = ["_ExposureAdjustment"];
  35846. var defines = "#define ";
  35847. if (operator === TonemappingOperator.Hable)
  35848. defines += "HABLE_TONEMAPPING";
  35849. else if (operator === TonemappingOperator.Reinhard)
  35850. defines += "REINHARD_TONEMAPPING";
  35851. else if (operator === TonemappingOperator.HejiDawson)
  35852. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35853. else if (operator === TonemappingOperator.Photographic)
  35854. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35855. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35856. this.onApply = function (effect) {
  35857. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35858. };
  35859. }
  35860. return TonemapPostProcess;
  35861. })(BABYLON.PostProcess);
  35862. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35863. })(BABYLON || (BABYLON = {}));
  35864. var BABYLON;
  35865. (function (BABYLON) {
  35866. var ReflectionProbe = (function () {
  35867. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35868. var _this = this;
  35869. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35870. this.name = name;
  35871. this._viewMatrix = BABYLON.Matrix.Identity();
  35872. this._target = BABYLON.Vector3.Zero();
  35873. this._add = BABYLON.Vector3.Zero();
  35874. this.position = BABYLON.Vector3.Zero();
  35875. this._scene = scene;
  35876. this._scene.reflectionProbes.push(this);
  35877. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35878. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35879. switch (faceIndex) {
  35880. case 0:
  35881. _this._add.copyFromFloats(1, 0, 0);
  35882. break;
  35883. case 1:
  35884. _this._add.copyFromFloats(-1, 0, 0);
  35885. break;
  35886. case 2:
  35887. _this._add.copyFromFloats(0, -1, 0);
  35888. break;
  35889. case 3:
  35890. _this._add.copyFromFloats(0, 1, 0);
  35891. break;
  35892. case 4:
  35893. _this._add.copyFromFloats(0, 0, 1);
  35894. break;
  35895. case 5:
  35896. _this._add.copyFromFloats(0, 0, -1);
  35897. break;
  35898. }
  35899. if (_this._attachedMesh) {
  35900. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35901. }
  35902. _this.position.addToRef(_this._add, _this._target);
  35903. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35904. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35905. };
  35906. this._renderTargetTexture.onAfterUnbind = function () {
  35907. scene.updateTransformMatrix(true);
  35908. };
  35909. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35910. }
  35911. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35912. get: function () {
  35913. return this._renderTargetTexture.refreshRate;
  35914. },
  35915. set: function (value) {
  35916. this._renderTargetTexture.refreshRate = value;
  35917. },
  35918. enumerable: true,
  35919. configurable: true
  35920. });
  35921. ReflectionProbe.prototype.getScene = function () {
  35922. return this._scene;
  35923. };
  35924. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35925. get: function () {
  35926. return this._renderTargetTexture;
  35927. },
  35928. enumerable: true,
  35929. configurable: true
  35930. });
  35931. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35932. get: function () {
  35933. return this._renderTargetTexture.renderList;
  35934. },
  35935. enumerable: true,
  35936. configurable: true
  35937. });
  35938. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35939. this._attachedMesh = mesh;
  35940. };
  35941. ReflectionProbe.prototype.dispose = function () {
  35942. var index = this._scene.reflectionProbes.indexOf(this);
  35943. if (index !== -1) {
  35944. // Remove from the scene if found
  35945. this._scene.reflectionProbes.splice(index, 1);
  35946. }
  35947. if (this._renderTargetTexture) {
  35948. this._renderTargetTexture.dispose();
  35949. this._renderTargetTexture = null;
  35950. }
  35951. };
  35952. return ReflectionProbe;
  35953. })();
  35954. BABYLON.ReflectionProbe = ReflectionProbe;
  35955. })(BABYLON || (BABYLON = {}));
  35956. var BABYLON;
  35957. (function (BABYLON) {
  35958. var SolidParticle = (function () {
  35959. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35960. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35961. this.position = BABYLON.Vector3.Zero(); // position
  35962. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35963. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35964. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35965. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35966. this.alive = true; // alive
  35967. this.idx = particleIndex;
  35968. this._pos = positionIndex;
  35969. this._model = model;
  35970. this.shapeId = shapeId;
  35971. this.idxInShape = idxInShape;
  35972. }
  35973. return SolidParticle;
  35974. })();
  35975. BABYLON.SolidParticle = SolidParticle;
  35976. var ModelShape = (function () {
  35977. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35978. this.shapeID = id;
  35979. this._shape = shape;
  35980. this._shapeUV = shapeUV;
  35981. this._positionFunction = posFunction;
  35982. this._vertexFunction = vtxFunction;
  35983. }
  35984. return ModelShape;
  35985. })();
  35986. BABYLON.ModelShape = ModelShape;
  35987. })(BABYLON || (BABYLON = {}));
  35988. var BABYLON;
  35989. (function (BABYLON) {
  35990. var SolidParticleSystem = (function () {
  35991. function SolidParticleSystem(name, scene, options) {
  35992. // public members
  35993. this.particles = new Array();
  35994. this.nbParticles = 0;
  35995. this.billboard = false;
  35996. this.counter = 0;
  35997. this.vars = {};
  35998. this._positions = new Array();
  35999. this._indices = new Array();
  36000. this._normals = new Array();
  36001. this._colors = new Array();
  36002. this._uvs = new Array();
  36003. this._index = 0; // indices index
  36004. this._updatable = true;
  36005. this._pickable = false;
  36006. this._alwaysVisible = false;
  36007. this._shapeCounter = 0;
  36008. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36009. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36010. this._computeParticleColor = true;
  36011. this._computeParticleTexture = true;
  36012. this._computeParticleRotation = true;
  36013. this._computeParticleVertex = false;
  36014. this._cam_axisZ = BABYLON.Vector3.Zero();
  36015. this._cam_axisY = BABYLON.Vector3.Zero();
  36016. this._cam_axisX = BABYLON.Vector3.Zero();
  36017. this._axisX = BABYLON.Axis.X;
  36018. this._axisY = BABYLON.Axis.Y;
  36019. this._axisZ = BABYLON.Axis.Z;
  36020. this._fakeCamPos = BABYLON.Vector3.Zero();
  36021. this._rotMatrix = new BABYLON.Matrix();
  36022. this._invertMatrix = new BABYLON.Matrix();
  36023. this._rotated = BABYLON.Vector3.Zero();
  36024. this._quaternion = new BABYLON.Quaternion();
  36025. this._vertex = BABYLON.Vector3.Zero();
  36026. this._normal = BABYLON.Vector3.Zero();
  36027. this._yaw = 0.0;
  36028. this._pitch = 0.0;
  36029. this._roll = 0.0;
  36030. this._halfroll = 0.0;
  36031. this._halfpitch = 0.0;
  36032. this._halfyaw = 0.0;
  36033. this._sinRoll = 0.0;
  36034. this._cosRoll = 0.0;
  36035. this._sinPitch = 0.0;
  36036. this._cosPitch = 0.0;
  36037. this._sinYaw = 0.0;
  36038. this._cosYaw = 0.0;
  36039. this._w = 0.0;
  36040. this.name = name;
  36041. this._scene = scene;
  36042. this._camera = scene.activeCamera;
  36043. this._pickable = options ? options.isPickable : false;
  36044. if (options && options.updatable) {
  36045. this._updatable = options.updatable;
  36046. }
  36047. else {
  36048. this._updatable = true;
  36049. }
  36050. if (this._pickable) {
  36051. this.pickedParticles = [];
  36052. }
  36053. }
  36054. // build the SPS mesh : returns the mesh
  36055. SolidParticleSystem.prototype.buildMesh = function () {
  36056. if (this.nbParticles === 0) {
  36057. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36058. this.addShape(triangle, 1);
  36059. triangle.dispose();
  36060. }
  36061. this._positions32 = new Float32Array(this._positions);
  36062. this._uvs32 = new Float32Array(this._uvs);
  36063. this._colors32 = new Float32Array(this._colors);
  36064. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36065. this._normals32 = new Float32Array(this._normals);
  36066. this._fixedNormal32 = new Float32Array(this._normals);
  36067. var vertexData = new BABYLON.VertexData();
  36068. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36069. vertexData.indices = this._indices;
  36070. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36071. if (this._uvs32) {
  36072. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36073. ;
  36074. }
  36075. if (this._colors32) {
  36076. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36077. }
  36078. var mesh = new BABYLON.Mesh(name, this._scene);
  36079. vertexData.applyToMesh(mesh, this._updatable);
  36080. this.mesh = mesh;
  36081. this.mesh.isPickable = this._pickable;
  36082. // free memory
  36083. this._positions = null;
  36084. this._normals = null;
  36085. this._uvs = null;
  36086. this._colors = null;
  36087. if (!this._updatable) {
  36088. this.particles.length = 0;
  36089. }
  36090. return mesh;
  36091. };
  36092. //reset copy
  36093. SolidParticleSystem.prototype._resetCopy = function () {
  36094. this._copy.position.x = 0;
  36095. this._copy.position.y = 0;
  36096. this._copy.position.z = 0;
  36097. this._copy.rotation.x = 0;
  36098. this._copy.rotation.y = 0;
  36099. this._copy.rotation.z = 0;
  36100. this._copy.quaternion = null;
  36101. this._copy.scale.x = 1;
  36102. this._copy.scale.y = 1;
  36103. this._copy.scale.z = 1;
  36104. this._copy.uvs.x = 0;
  36105. this._copy.uvs.y = 0;
  36106. this._copy.uvs.z = 1;
  36107. this._copy.uvs.w = 1;
  36108. this._copy.color = null;
  36109. };
  36110. // _meshBuilder : inserts the shape model in the global SPS mesh
  36111. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36112. var i;
  36113. var u = 0;
  36114. var c = 0;
  36115. this._resetCopy();
  36116. if (options && options.positionFunction) {
  36117. options.positionFunction(this._copy, idx, idxInShape);
  36118. }
  36119. if (this._copy.quaternion) {
  36120. this._quaternion.x = this._copy.quaternion.x;
  36121. this._quaternion.y = this._copy.quaternion.y;
  36122. this._quaternion.z = this._copy.quaternion.z;
  36123. this._quaternion.w = this._copy.quaternion.w;
  36124. }
  36125. else {
  36126. this._yaw = this._copy.rotation.y;
  36127. this._pitch = this._copy.rotation.x;
  36128. this._roll = this._copy.rotation.z;
  36129. this._quaternionRotationYPR();
  36130. }
  36131. this._quaternionToRotationMatrix();
  36132. for (i = 0; i < shape.length; i++) {
  36133. this._vertex.x = shape[i].x;
  36134. this._vertex.y = shape[i].y;
  36135. this._vertex.z = shape[i].z;
  36136. if (options && options.vertexFunction) {
  36137. options.vertexFunction(this._copy, this._vertex, i);
  36138. }
  36139. this._vertex.x *= this._copy.scale.x;
  36140. this._vertex.y *= this._copy.scale.y;
  36141. this._vertex.z *= this._copy.scale.z;
  36142. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36143. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36144. if (meshUV) {
  36145. 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);
  36146. u += 2;
  36147. }
  36148. if (this._copy.color) {
  36149. this._color = this._copy.color;
  36150. }
  36151. else if (meshCol && meshCol[c]) {
  36152. this._color.r = meshCol[c];
  36153. this._color.g = meshCol[c + 1];
  36154. this._color.b = meshCol[c + 2];
  36155. this._color.a = meshCol[c + 3];
  36156. }
  36157. else {
  36158. this._color.r = 1;
  36159. this._color.g = 1;
  36160. this._color.b = 1;
  36161. this._color.a = 1;
  36162. }
  36163. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36164. c += 4;
  36165. }
  36166. for (i = 0; i < meshInd.length; i++) {
  36167. indices.push(p + meshInd[i]);
  36168. }
  36169. if (this._pickable) {
  36170. var nbfaces = meshInd.length / 3;
  36171. for (i = 0; i < nbfaces; i++) {
  36172. this.pickedParticles.push({ idx: idx, faceId: i });
  36173. }
  36174. }
  36175. };
  36176. // returns a shape array from positions array
  36177. SolidParticleSystem.prototype._posToShape = function (positions) {
  36178. var shape = [];
  36179. for (var i = 0; i < positions.length; i += 3) {
  36180. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36181. }
  36182. return shape;
  36183. };
  36184. // returns a shapeUV array from a Vector4 uvs
  36185. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36186. var shapeUV = [];
  36187. if (uvs) {
  36188. for (var i = 0; i < uvs.length; i++)
  36189. shapeUV.push(uvs[i]);
  36190. }
  36191. return shapeUV;
  36192. };
  36193. // adds a new particle object in the particles array
  36194. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36195. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36196. };
  36197. // add solid particles from a shape model in the particles array
  36198. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36199. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36200. var meshInd = mesh.getIndices();
  36201. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36202. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36203. var shape = this._posToShape(meshPos);
  36204. var shapeUV = this._uvsToShapeUV(meshUV);
  36205. var posfunc = options ? options.positionFunction : null;
  36206. var vtxfunc = options ? options.vertexFunction : null;
  36207. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36208. // particles
  36209. var idx = this.nbParticles;
  36210. for (var i = 0; i < nb; i++) {
  36211. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36212. if (this._updatable) {
  36213. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36214. }
  36215. this._index += shape.length;
  36216. idx++;
  36217. }
  36218. this.nbParticles += nb;
  36219. this._shapeCounter++;
  36220. return this._shapeCounter;
  36221. };
  36222. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36223. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36224. this._resetCopy();
  36225. if (particle._model._positionFunction) {
  36226. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36227. }
  36228. if (this._copy.quaternion) {
  36229. this._quaternion.x = this._copy.quaternion.x;
  36230. this._quaternion.y = this._copy.quaternion.y;
  36231. this._quaternion.z = this._copy.quaternion.z;
  36232. this._quaternion.w = this._copy.quaternion.w;
  36233. }
  36234. else {
  36235. this._yaw = this._copy.rotation.y;
  36236. this._pitch = this._copy.rotation.x;
  36237. this._roll = this._copy.rotation.z;
  36238. this._quaternionRotationYPR();
  36239. }
  36240. this._quaternionToRotationMatrix();
  36241. this._shape = particle._model._shape;
  36242. for (var pt = 0; pt < this._shape.length; pt++) {
  36243. this._vertex.x = this._shape[pt].x;
  36244. this._vertex.y = this._shape[pt].y;
  36245. this._vertex.z = this._shape[pt].z;
  36246. if (particle._model._vertexFunction) {
  36247. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36248. }
  36249. this._vertex.x *= this._copy.scale.x;
  36250. this._vertex.y *= this._copy.scale.y;
  36251. this._vertex.z *= this._copy.scale.z;
  36252. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36253. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36254. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36255. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36256. }
  36257. particle.position.x = 0;
  36258. particle.position.y = 0;
  36259. particle.position.z = 0;
  36260. particle.rotation.x = 0;
  36261. particle.rotation.y = 0;
  36262. particle.rotation.z = 0;
  36263. particle.quaternion = null;
  36264. particle.scale.x = 1;
  36265. particle.scale.y = 1;
  36266. particle.scale.z = 1;
  36267. };
  36268. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36269. SolidParticleSystem.prototype.rebuildMesh = function () {
  36270. for (var p = 0; p < this.particles.length; p++) {
  36271. this._rebuildParticle(this.particles[p]);
  36272. }
  36273. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36274. };
  36275. // sets all the particles : updates the VBO
  36276. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36277. if (start === void 0) { start = 0; }
  36278. if (end === void 0) { end = this.nbParticles - 1; }
  36279. if (update === void 0) { update = true; }
  36280. if (!this._updatable) {
  36281. return;
  36282. }
  36283. // custom beforeUpdate
  36284. this.beforeUpdateParticles(start, end, update);
  36285. this._cam_axisX.x = 1;
  36286. this._cam_axisX.y = 0;
  36287. this._cam_axisX.z = 0;
  36288. this._cam_axisY.x = 0;
  36289. this._cam_axisY.y = 1;
  36290. this._cam_axisY.z = 0;
  36291. this._cam_axisZ.x = 0;
  36292. this._cam_axisZ.y = 0;
  36293. this._cam_axisZ.z = 1;
  36294. // if the particles will always face the camera
  36295. if (this.billboard) {
  36296. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36297. this._yaw = this.mesh.rotation.y;
  36298. this._pitch = this.mesh.rotation.x;
  36299. this._roll = this.mesh.rotation.z;
  36300. this._quaternionRotationYPR();
  36301. this._quaternionToRotationMatrix();
  36302. this._rotMatrix.invertToRef(this._invertMatrix);
  36303. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36304. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36305. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36306. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36307. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36308. this._cam_axisY.normalize();
  36309. this._cam_axisX.normalize();
  36310. this._cam_axisZ.normalize();
  36311. }
  36312. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36313. var idx = 0;
  36314. var index = 0;
  36315. var colidx = 0;
  36316. var colorIndex = 0;
  36317. var uvidx = 0;
  36318. var uvIndex = 0;
  36319. // particle loop
  36320. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36321. for (var p = start; p <= end; p++) {
  36322. this._particle = this.particles[p];
  36323. this._shape = this._particle._model._shape;
  36324. this._shapeUV = this._particle._model._shapeUV;
  36325. // call to custom user function to update the particle properties
  36326. this.updateParticle(this._particle);
  36327. // particle rotation matrix
  36328. if (this.billboard) {
  36329. this._particle.rotation.x = 0.0;
  36330. this._particle.rotation.y = 0.0;
  36331. }
  36332. if (this._computeParticleRotation) {
  36333. if (this._particle.quaternion) {
  36334. this._quaternion.x = this._particle.quaternion.x;
  36335. this._quaternion.y = this._particle.quaternion.y;
  36336. this._quaternion.z = this._particle.quaternion.z;
  36337. this._quaternion.w = this._particle.quaternion.w;
  36338. }
  36339. else {
  36340. this._yaw = this._particle.rotation.y;
  36341. this._pitch = this._particle.rotation.x;
  36342. this._roll = this._particle.rotation.z;
  36343. this._quaternionRotationYPR();
  36344. }
  36345. this._quaternionToRotationMatrix();
  36346. }
  36347. for (var pt = 0; pt < this._shape.length; pt++) {
  36348. idx = index + pt * 3;
  36349. colidx = colorIndex + pt * 4;
  36350. uvidx = uvIndex + pt * 2;
  36351. this._vertex.x = this._shape[pt].x;
  36352. this._vertex.y = this._shape[pt].y;
  36353. this._vertex.z = this._shape[pt].z;
  36354. if (this._computeParticleVertex) {
  36355. this.updateParticleVertex(this._particle, this._vertex, pt);
  36356. }
  36357. // positions
  36358. this._vertex.x *= this._particle.scale.x;
  36359. this._vertex.y *= this._particle.scale.y;
  36360. this._vertex.z *= this._particle.scale.z;
  36361. 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];
  36362. 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;
  36363. 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;
  36364. 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;
  36365. 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;
  36366. 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;
  36367. 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;
  36368. // normals : if the particles can't be morphed then just rotate the normals
  36369. if (!this._computeParticleVertex && !this.billboard) {
  36370. this._normal.x = this._fixedNormal32[idx];
  36371. this._normal.y = this._fixedNormal32[idx + 1];
  36372. this._normal.z = this._fixedNormal32[idx + 2];
  36373. 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];
  36374. 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;
  36375. 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;
  36376. 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;
  36377. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36378. 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;
  36379. 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;
  36380. }
  36381. if (this._computeParticleColor) {
  36382. this._colors32[colidx] = this._particle.color.r;
  36383. this._colors32[colidx + 1] = this._particle.color.g;
  36384. this._colors32[colidx + 2] = this._particle.color.b;
  36385. this._colors32[colidx + 3] = this._particle.color.a;
  36386. }
  36387. if (this._computeParticleTexture) {
  36388. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36389. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36390. }
  36391. }
  36392. index = idx + 3;
  36393. colorIndex = colidx + 4;
  36394. uvIndex = uvidx + 2;
  36395. }
  36396. if (update) {
  36397. if (this._computeParticleColor) {
  36398. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36399. }
  36400. if (this._computeParticleTexture) {
  36401. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36402. }
  36403. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36404. if (!this.mesh.areNormalsFrozen) {
  36405. if (this._computeParticleVertex || this.billboard) {
  36406. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36407. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36408. for (var i = 0; i < this._normals32.length; i++) {
  36409. this._fixedNormal32[i] = this._normals32[i];
  36410. }
  36411. }
  36412. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36413. }
  36414. }
  36415. this.afterUpdateParticles(start, end, update);
  36416. };
  36417. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36418. this._halfroll = this._roll * 0.5;
  36419. this._halfpitch = this._pitch * 0.5;
  36420. this._halfyaw = this._yaw * 0.5;
  36421. this._sinRoll = Math.sin(this._halfroll);
  36422. this._cosRoll = Math.cos(this._halfroll);
  36423. this._sinPitch = Math.sin(this._halfpitch);
  36424. this._cosPitch = Math.cos(this._halfpitch);
  36425. this._sinYaw = Math.sin(this._halfyaw);
  36426. this._cosYaw = Math.cos(this._halfyaw);
  36427. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36428. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36429. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36430. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36431. };
  36432. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36433. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36434. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36435. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36436. this._rotMatrix.m[3] = 0;
  36437. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36438. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36439. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36440. this._rotMatrix.m[7] = 0;
  36441. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36442. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36443. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36444. this._rotMatrix.m[11] = 0;
  36445. this._rotMatrix.m[12] = 0;
  36446. this._rotMatrix.m[13] = 0;
  36447. this._rotMatrix.m[14] = 0;
  36448. this._rotMatrix.m[15] = 1.0;
  36449. };
  36450. // dispose the SPS
  36451. SolidParticleSystem.prototype.dispose = function () {
  36452. this.mesh.dispose();
  36453. this.vars = null;
  36454. // drop references to internal big arrays for the GC
  36455. this._positions = null;
  36456. this._indices = null;
  36457. this._normals = null;
  36458. this._uvs = null;
  36459. this._colors = null;
  36460. this._positions32 = null;
  36461. this._normals32 = null;
  36462. this._fixedNormal32 = null;
  36463. this._uvs32 = null;
  36464. this._colors32 = null;
  36465. this.pickedParticles = null;
  36466. };
  36467. // Visibilty helpers
  36468. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36469. this.mesh.refreshBoundingInfo();
  36470. };
  36471. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36472. // getter and setter
  36473. get: function () {
  36474. return this._alwaysVisible;
  36475. },
  36476. set: function (val) {
  36477. this._alwaysVisible = val;
  36478. this.mesh.alwaysSelectAsActiveMesh = val;
  36479. },
  36480. enumerable: true,
  36481. configurable: true
  36482. });
  36483. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36484. // getters
  36485. get: function () {
  36486. return this._computeParticleRotation;
  36487. },
  36488. // Optimizer setters
  36489. set: function (val) {
  36490. this._computeParticleRotation = val;
  36491. },
  36492. enumerable: true,
  36493. configurable: true
  36494. });
  36495. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36496. get: function () {
  36497. return this._computeParticleColor;
  36498. },
  36499. set: function (val) {
  36500. this._computeParticleColor = val;
  36501. },
  36502. enumerable: true,
  36503. configurable: true
  36504. });
  36505. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36506. get: function () {
  36507. return this._computeParticleTexture;
  36508. },
  36509. set: function (val) {
  36510. this._computeParticleTexture = val;
  36511. },
  36512. enumerable: true,
  36513. configurable: true
  36514. });
  36515. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36516. get: function () {
  36517. return this._computeParticleVertex;
  36518. },
  36519. set: function (val) {
  36520. this._computeParticleVertex = val;
  36521. },
  36522. enumerable: true,
  36523. configurable: true
  36524. });
  36525. // =======================================================================
  36526. // Particle behavior logic
  36527. // these following methods may be overwritten by the user to fit his needs
  36528. // init : sets all particles first values and calls updateParticle to set them in space
  36529. // can be overwritten by the user
  36530. SolidParticleSystem.prototype.initParticles = function () {
  36531. };
  36532. // recycles a particle : can by overwritten by the user
  36533. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36534. return particle;
  36535. };
  36536. // updates a particle : can be overwritten by the user
  36537. // will be called on each particle by setParticles() :
  36538. // ex : just set a particle position or velocity and recycle conditions
  36539. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36540. return particle;
  36541. };
  36542. // updates a vertex of a particle : can be overwritten by the user
  36543. // will be called on each vertex particle by setParticles() :
  36544. // particle : the current particle
  36545. // vertex : the current index of the current particle
  36546. // pt : the index of the current vertex in the particle shape
  36547. // ex : just set a vertex particle position
  36548. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36549. return vertex;
  36550. };
  36551. // will be called before any other treatment by setParticles()
  36552. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36553. };
  36554. // will be called after all setParticles() treatments
  36555. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36556. };
  36557. return SolidParticleSystem;
  36558. })();
  36559. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36560. })(BABYLON || (BABYLON = {}));
  36561. 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}","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}","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_FIXED\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_FIXED\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_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.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\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * 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 * 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_FIXED\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_FIXED\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}","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}","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}","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}","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}"};
  36562. 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.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},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,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,W=s*y-h*u,N=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*S+o*D)*b,t.m[7]=(i*q-r*Z+o*W)*b,t.m[11]=-(i*S-n*Z+o*N)*b,t.m[15]=(i*D-n*W+r*N)*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;\nt.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,n.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.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},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.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);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={}));";
  36563. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36564. module.exports = BABYLON;
  36565. };