babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformNormal = function (vector, transformation) {
  680. var result = Vector3.Zero();
  681. Vector3.TransformNormalToRef(vector, transformation, result);
  682. return result;
  683. };
  684. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  685. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  686. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  687. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  688. };
  689. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  690. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  691. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  692. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  693. };
  694. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  695. var squared = amount * amount;
  696. var cubed = amount * squared;
  697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  703. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  704. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  705. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Clamp = function (value, min, max) {
  709. var x = value.x;
  710. x = (x > max.x) ? max.x : x;
  711. x = (x < min.x) ? min.x : x;
  712. var y = value.y;
  713. y = (y > max.y) ? max.y : y;
  714. y = (y < min.y) ? min.y : y;
  715. var z = value.z;
  716. z = (z > max.z) ? max.z : z;
  717. z = (z < min.z) ? min.z : z;
  718. return new Vector3(x, y, z);
  719. };
  720. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  721. var squared = amount * amount;
  722. var cubed = amount * squared;
  723. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  724. var part2 = (-2.0 * cubed) + (3.0 * squared);
  725. var part3 = (cubed - (2.0 * squared)) + amount;
  726. var part4 = cubed - squared;
  727. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  728. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  729. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Lerp = function (start, end, amount) {
  733. var x = start.x + ((end.x - start.x) * amount);
  734. var y = start.y + ((end.y - start.y) * amount);
  735. var z = start.z + ((end.z - start.z) * amount);
  736. return new Vector3(x, y, z);
  737. };
  738. Vector3.Dot = function (left, right) {
  739. return (left.x * right.x + left.y * right.y + left.z * right.z);
  740. };
  741. Vector3.Cross = function (left, right) {
  742. var result = Vector3.Zero();
  743. Vector3.CrossToRef(left, right, result);
  744. return result;
  745. };
  746. Vector3.CrossToRef = function (left, right, result) {
  747. result.x = left.y * right.z - left.z * right.y;
  748. result.y = left.z * right.x - left.x * right.z;
  749. result.z = left.x * right.y - left.y * right.x;
  750. };
  751. Vector3.Normalize = function (vector) {
  752. var result = Vector3.Zero();
  753. Vector3.NormalizeToRef(vector, result);
  754. return result;
  755. };
  756. Vector3.NormalizeToRef = function (vector, result) {
  757. result.copyFrom(vector);
  758. result.normalize();
  759. };
  760. Vector3.Project = function (vector, world, transform, viewport) {
  761. var cw = viewport.width;
  762. var ch = viewport.height;
  763. var cx = viewport.x;
  764. var cy = viewport.y;
  765. 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);
  766. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  767. return Vector3.TransformCoordinates(vector, finalMatrix);
  768. };
  769. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  770. var matrix = world.multiply(transform);
  771. matrix.invert();
  772. source.x = source.x / viewportWidth * 2 - 1;
  773. source.y = -(source.y / viewportHeight * 2 - 1);
  774. var vector = Vector3.TransformCoordinates(source, matrix);
  775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  776. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  777. vector = vector.scale(1.0 / num);
  778. }
  779. return vector;
  780. };
  781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  782. var matrix = world.multiply(view).multiply(projection);
  783. matrix.invert();
  784. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  785. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  786. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  787. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  788. vector = vector.scale(1.0 / num);
  789. }
  790. return vector;
  791. };
  792. Vector3.Minimize = function (left, right) {
  793. var min = left.clone();
  794. min.MinimizeInPlace(right);
  795. return min;
  796. };
  797. Vector3.Maximize = function (left, right) {
  798. var max = left.clone();
  799. max.MaximizeInPlace(right);
  800. return max;
  801. };
  802. Vector3.Distance = function (value1, value2) {
  803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  804. };
  805. Vector3.DistanceSquared = function (value1, value2) {
  806. var x = value1.x - value2.x;
  807. var y = value1.y - value2.y;
  808. var z = value1.z - value2.z;
  809. return (x * x) + (y * y) + (z * z);
  810. };
  811. Vector3.Center = function (value1, value2) {
  812. var center = value1.add(value2);
  813. center.scaleInPlace(0.5);
  814. return center;
  815. };
  816. /**
  817. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  819. * to something in order to rotate it from its local system to the given target system.
  820. */
  821. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  822. var rotation = Vector3.Zero();
  823. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  824. return rotation;
  825. };
  826. /**
  827. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  828. */
  829. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  830. var u = Vector3.Normalize(axis1);
  831. var w = Vector3.Normalize(axis3);
  832. // world axis
  833. var X = Axis.X;
  834. var Y = Axis.Y;
  835. // equation unknowns and vars
  836. var yaw = 0.0;
  837. var pitch = 0.0;
  838. var roll = 0.0;
  839. var x = 0.0;
  840. var y = 0.0;
  841. var z = 0.0;
  842. var t = 0.0;
  843. var sign = -1.0;
  844. var nbRevert = 0;
  845. var cross;
  846. var dot = 0.0;
  847. // step 1 : rotation around w
  848. // Rv3(u) = u1, and u1 belongs to plane xOz
  849. // Rv3(w) = w1 = w invariant
  850. var u1;
  851. var v1;
  852. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  853. z = 1.0;
  854. }
  855. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  856. x = 1.0;
  857. }
  858. else {
  859. t = w.z / w.x;
  860. x = -t * Math.sqrt(1 / (1 + t * t));
  861. z = Math.sqrt(1 / (1 + t * t));
  862. }
  863. u1 = new Vector3(x, y, z);
  864. u1.normalize();
  865. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  866. v1.normalize();
  867. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  868. cross.normalize();
  869. if (Vector3.Dot(w, cross) < 0) {
  870. sign = 1.0;
  871. }
  872. dot = Vector3.Dot(u, u1);
  873. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  874. roll = Math.acos(dot) * sign;
  875. if (Vector3.Dot(u1, X) < 0) {
  876. roll = Math.PI + roll;
  877. u1 = u1.scaleInPlace(-1);
  878. v1 = v1.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 2 : rotate around u1
  882. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  883. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  884. var w2;
  885. var v2;
  886. x = 0.0;
  887. y = 0.0;
  888. z = 0.0;
  889. sign = -1;
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. x = 1.0;
  892. }
  893. else {
  894. t = u1.z / u1.x;
  895. x = -t * Math.sqrt(1 / (1 + t * t));
  896. z = Math.sqrt(1 / (1 + t * t));
  897. }
  898. w2 = new Vector3(x, y, z);
  899. w2.normalize();
  900. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  901. v2.normalize();
  902. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  903. cross.normalize();
  904. if (Vector3.Dot(u1, cross) < 0) {
  905. sign = 1.0;
  906. }
  907. dot = Vector3.Dot(w, w2);
  908. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  909. pitch = Math.acos(dot) * sign;
  910. if (Vector3.Dot(v2, Y) < 0) {
  911. pitch = Math.PI + pitch;
  912. v2 = v2.scaleInPlace(-1);
  913. w2 = w2.scaleInPlace(-1);
  914. nbRevert++;
  915. }
  916. // step 3 : rotate around v2
  917. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  918. sign = -1;
  919. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  920. cross.normalize();
  921. if (Vector3.Dot(cross, Y) < 0) {
  922. sign = 1.0;
  923. }
  924. dot = Vector3.Dot(u1, X);
  925. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  926. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  927. if (dot < 0 && nbRevert < 2) {
  928. yaw = Math.PI + yaw;
  929. }
  930. ref.x = pitch;
  931. ref.y = yaw;
  932. ref.z = roll;
  933. };
  934. return Vector3;
  935. })();
  936. BABYLON.Vector3 = Vector3;
  937. //Vector4 class created for EulerAngle class conversion to Quaternion
  938. var Vector4 = (function () {
  939. function Vector4(x, y, z, w) {
  940. this.x = x;
  941. this.y = y;
  942. this.z = z;
  943. this.w = w;
  944. }
  945. Vector4.prototype.toString = function () {
  946. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  947. };
  948. // Operators
  949. Vector4.prototype.asArray = function () {
  950. var result = [];
  951. this.toArray(result, 0);
  952. return result;
  953. };
  954. Vector4.prototype.toArray = function (array, index) {
  955. if (index === undefined) {
  956. index = 0;
  957. }
  958. array[index] = this.x;
  959. array[index + 1] = this.y;
  960. array[index + 2] = this.z;
  961. array[index + 3] = this.w;
  962. return this;
  963. };
  964. Vector4.prototype.addInPlace = function (otherVector) {
  965. this.x += otherVector.x;
  966. this.y += otherVector.y;
  967. this.z += otherVector.z;
  968. this.w += otherVector.w;
  969. return this;
  970. };
  971. Vector4.prototype.add = function (otherVector) {
  972. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  973. };
  974. Vector4.prototype.addToRef = function (otherVector, result) {
  975. result.x = this.x + otherVector.x;
  976. result.y = this.y + otherVector.y;
  977. result.z = this.z + otherVector.z;
  978. result.w = this.w + otherVector.w;
  979. return this;
  980. };
  981. Vector4.prototype.subtractInPlace = function (otherVector) {
  982. this.x -= otherVector.x;
  983. this.y -= otherVector.y;
  984. this.z -= otherVector.z;
  985. this.w -= otherVector.w;
  986. return this;
  987. };
  988. Vector4.prototype.subtract = function (otherVector) {
  989. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  990. };
  991. Vector4.prototype.subtractToRef = function (otherVector, result) {
  992. result.x = this.x - otherVector.x;
  993. result.y = this.y - otherVector.y;
  994. result.z = this.z - otherVector.z;
  995. result.w = this.w - otherVector.w;
  996. return this;
  997. };
  998. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  999. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1000. };
  1001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = this.x - x;
  1003. result.y = this.y - y;
  1004. result.z = this.z - z;
  1005. result.w = this.w - w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.negate = function () {
  1009. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1010. };
  1011. Vector4.prototype.scaleInPlace = function (scale) {
  1012. this.x *= scale;
  1013. this.y *= scale;
  1014. this.z *= scale;
  1015. this.w *= scale;
  1016. return this;
  1017. };
  1018. Vector4.prototype.scale = function (scale) {
  1019. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1020. };
  1021. Vector4.prototype.scaleToRef = function (scale, result) {
  1022. result.x = this.x * scale;
  1023. result.y = this.y * scale;
  1024. result.z = this.z * scale;
  1025. result.w = this.w * scale;
  1026. };
  1027. Vector4.prototype.equals = function (otherVector) {
  1028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1029. };
  1030. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1031. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1032. return otherVector
  1033. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1034. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1035. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1036. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1037. };
  1038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1039. return this.x === x && this.y === y && this.z === z && this.w === w;
  1040. };
  1041. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1042. this.x *= otherVector.x;
  1043. this.y *= otherVector.y;
  1044. this.z *= otherVector.z;
  1045. this.w *= otherVector.w;
  1046. return this;
  1047. };
  1048. Vector4.prototype.multiply = function (otherVector) {
  1049. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1050. };
  1051. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1052. result.x = this.x * otherVector.x;
  1053. result.y = this.y * otherVector.y;
  1054. result.z = this.z * otherVector.z;
  1055. result.w = this.w * otherVector.w;
  1056. return this;
  1057. };
  1058. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1059. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1060. };
  1061. Vector4.prototype.divide = function (otherVector) {
  1062. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1063. };
  1064. Vector4.prototype.divideToRef = function (otherVector, result) {
  1065. result.x = this.x / otherVector.x;
  1066. result.y = this.y / otherVector.y;
  1067. result.z = this.z / otherVector.z;
  1068. result.w = this.w / otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.MinimizeInPlace = function (other) {
  1072. if (other.x < this.x)
  1073. this.x = other.x;
  1074. if (other.y < this.y)
  1075. this.y = other.y;
  1076. if (other.z < this.z)
  1077. this.z = other.z;
  1078. if (other.w < this.w)
  1079. this.w = other.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.MaximizeInPlace = function (other) {
  1083. if (other.x > this.x)
  1084. this.x = other.x;
  1085. if (other.y > this.y)
  1086. this.y = other.y;
  1087. if (other.z > this.z)
  1088. this.z = other.z;
  1089. if (other.w > this.w)
  1090. this.w = other.w;
  1091. return this;
  1092. };
  1093. // Properties
  1094. Vector4.prototype.length = function () {
  1095. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1096. };
  1097. Vector4.prototype.lengthSquared = function () {
  1098. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1099. };
  1100. // Methods
  1101. Vector4.prototype.normalize = function () {
  1102. var len = this.length();
  1103. if (len === 0)
  1104. return this;
  1105. var num = 1.0 / len;
  1106. this.x *= num;
  1107. this.y *= num;
  1108. this.z *= num;
  1109. this.w *= num;
  1110. return this;
  1111. };
  1112. Vector4.prototype.clone = function () {
  1113. return new Vector4(this.x, this.y, this.z, this.w);
  1114. };
  1115. Vector4.prototype.copyFrom = function (source) {
  1116. this.x = source.x;
  1117. this.y = source.y;
  1118. this.z = source.z;
  1119. this.w = source.w;
  1120. return this;
  1121. };
  1122. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1123. this.x = x;
  1124. this.y = y;
  1125. this.z = z;
  1126. this.w = w;
  1127. return this;
  1128. };
  1129. // Statics
  1130. Vector4.FromArray = function (array, offset) {
  1131. if (!offset) {
  1132. offset = 0;
  1133. }
  1134. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1135. };
  1136. Vector4.FromArrayToRef = function (array, offset, result) {
  1137. result.x = array[offset];
  1138. result.y = array[offset + 1];
  1139. result.z = array[offset + 2];
  1140. result.w = array[offset + 3];
  1141. };
  1142. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1143. result.x = array[offset];
  1144. result.y = array[offset + 1];
  1145. result.z = array[offset + 2];
  1146. result.w = array[offset + 3];
  1147. };
  1148. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1149. result.x = x;
  1150. result.y = y;
  1151. result.z = z;
  1152. result.w = w;
  1153. };
  1154. Vector4.Zero = function () {
  1155. return new Vector4(0, 0, 0, 0);
  1156. };
  1157. Vector4.Normalize = function (vector) {
  1158. var result = Vector4.Zero();
  1159. Vector4.NormalizeToRef(vector, result);
  1160. return result;
  1161. };
  1162. Vector4.NormalizeToRef = function (vector, result) {
  1163. result.copyFrom(vector);
  1164. result.normalize();
  1165. };
  1166. Vector4.Minimize = function (left, right) {
  1167. var min = left.clone();
  1168. min.MinimizeInPlace(right);
  1169. return min;
  1170. };
  1171. Vector4.Maximize = function (left, right) {
  1172. var max = left.clone();
  1173. max.MaximizeInPlace(right);
  1174. return max;
  1175. };
  1176. Vector4.Distance = function (value1, value2) {
  1177. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1178. };
  1179. Vector4.DistanceSquared = function (value1, value2) {
  1180. var x = value1.x - value2.x;
  1181. var y = value1.y - value2.y;
  1182. var z = value1.z - value2.z;
  1183. var w = value1.w - value2.w;
  1184. return (x * x) + (y * y) + (z * z) + (w * w);
  1185. };
  1186. Vector4.Center = function (value1, value2) {
  1187. var center = value1.add(value2);
  1188. center.scaleInPlace(0.5);
  1189. return center;
  1190. };
  1191. return Vector4;
  1192. })();
  1193. BABYLON.Vector4 = Vector4;
  1194. var Quaternion = (function () {
  1195. function Quaternion(x, y, z, w) {
  1196. if (x === void 0) { x = 0; }
  1197. if (y === void 0) { y = 0; }
  1198. if (z === void 0) { z = 0; }
  1199. if (w === void 0) { w = 1; }
  1200. this.x = x;
  1201. this.y = y;
  1202. this.z = z;
  1203. this.w = w;
  1204. }
  1205. Quaternion.prototype.toString = function () {
  1206. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1207. };
  1208. Quaternion.prototype.asArray = function () {
  1209. return [this.x, this.y, this.z, this.w];
  1210. };
  1211. Quaternion.prototype.equals = function (otherQuaternion) {
  1212. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1213. };
  1214. Quaternion.prototype.clone = function () {
  1215. return new Quaternion(this.x, this.y, this.z, this.w);
  1216. };
  1217. Quaternion.prototype.copyFrom = function (other) {
  1218. this.x = other.x;
  1219. this.y = other.y;
  1220. this.z = other.z;
  1221. this.w = other.w;
  1222. return this;
  1223. };
  1224. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1225. this.x = x;
  1226. this.y = y;
  1227. this.z = z;
  1228. this.w = w;
  1229. return this;
  1230. };
  1231. Quaternion.prototype.add = function (other) {
  1232. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1233. };
  1234. Quaternion.prototype.subtract = function (other) {
  1235. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1236. };
  1237. Quaternion.prototype.scale = function (value) {
  1238. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1239. };
  1240. Quaternion.prototype.multiply = function (q1) {
  1241. var result = new Quaternion(0, 0, 0, 1.0);
  1242. this.multiplyToRef(q1, result);
  1243. return result;
  1244. };
  1245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1250. result.copyFromFloats(x, y, z, w);
  1251. return this;
  1252. };
  1253. Quaternion.prototype.multiplyInPlace = function (q1) {
  1254. this.multiplyToRef(q1, this);
  1255. return this;
  1256. };
  1257. Quaternion.prototype.length = function () {
  1258. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1259. };
  1260. Quaternion.prototype.normalize = function () {
  1261. var length = 1.0 / this.length();
  1262. this.x *= length;
  1263. this.y *= length;
  1264. this.z *= length;
  1265. this.w *= length;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.toEulerAngles = function () {
  1269. var result = Vector3.Zero();
  1270. this.toEulerAnglesToRef(result);
  1271. return result;
  1272. };
  1273. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1274. //result is an EulerAngles in the in the z-x-z convention
  1275. var qx = this.x;
  1276. var qy = this.y;
  1277. var qz = this.z;
  1278. var qw = this.w;
  1279. var qxy = qx * qy;
  1280. var qxz = qx * qz;
  1281. var qwy = qw * qy;
  1282. var qwz = qw * qz;
  1283. var qwx = qw * qx;
  1284. var qyz = qy * qz;
  1285. var sqx = qx * qx;
  1286. var sqy = qy * qy;
  1287. var determinant = sqx + sqy;
  1288. if (determinant !== 0.000 && determinant !== 1.000) {
  1289. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1290. result.y = Math.acos(1 - 2 * determinant);
  1291. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1292. }
  1293. else {
  1294. if (determinant === 0.0) {
  1295. result.x = 0.0;
  1296. result.y = 0.0;
  1297. 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)
  1298. }
  1299. else {
  1300. 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)
  1301. result.y = Math.PI;
  1302. result.z = 0.0;
  1303. }
  1304. }
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toRotationMatrix = function (result) {
  1308. var xx = this.x * this.x;
  1309. var yy = this.y * this.y;
  1310. var zz = this.z * this.z;
  1311. var xy = this.x * this.y;
  1312. var zw = this.z * this.w;
  1313. var zx = this.z * this.x;
  1314. var yw = this.y * this.w;
  1315. var yz = this.y * this.z;
  1316. var xw = this.x * this.w;
  1317. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1318. result.m[1] = 2.0 * (xy + zw);
  1319. result.m[2] = 2.0 * (zx - yw);
  1320. result.m[3] = 0;
  1321. result.m[4] = 2.0 * (xy - zw);
  1322. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1323. result.m[6] = 2.0 * (yz + xw);
  1324. result.m[7] = 0;
  1325. result.m[8] = 2.0 * (zx + yw);
  1326. result.m[9] = 2.0 * (yz - xw);
  1327. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1328. result.m[11] = 0;
  1329. result.m[12] = 0;
  1330. result.m[13] = 0;
  1331. result.m[14] = 0;
  1332. result.m[15] = 1.0;
  1333. return this;
  1334. };
  1335. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1336. Quaternion.FromRotationMatrixToRef(matrix, this);
  1337. return this;
  1338. };
  1339. // Statics
  1340. Quaternion.FromRotationMatrix = function (matrix) {
  1341. var result = new Quaternion();
  1342. Quaternion.FromRotationMatrixToRef(matrix, result);
  1343. return result;
  1344. };
  1345. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1346. var data = matrix.m;
  1347. var m11 = data[0], m12 = data[4], m13 = data[8];
  1348. var m21 = data[1], m22 = data[5], m23 = data[9];
  1349. var m31 = data[2], m32 = data[6], m33 = data[10];
  1350. var trace = m11 + m22 + m33;
  1351. var s;
  1352. if (trace > 0) {
  1353. s = 0.5 / Math.sqrt(trace + 1.0);
  1354. result.w = 0.25 / s;
  1355. result.x = (m32 - m23) * s;
  1356. result.y = (m13 - m31) * s;
  1357. result.z = (m21 - m12) * s;
  1358. }
  1359. else if (m11 > m22 && m11 > m33) {
  1360. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1361. result.w = (m32 - m23) / s;
  1362. result.x = 0.25 * s;
  1363. result.y = (m12 + m21) / s;
  1364. result.z = (m13 + m31) / s;
  1365. }
  1366. else if (m22 > m33) {
  1367. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1368. result.w = (m13 - m31) / s;
  1369. result.x = (m12 + m21) / s;
  1370. result.y = 0.25 * s;
  1371. result.z = (m23 + m32) / s;
  1372. }
  1373. else {
  1374. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1375. result.w = (m21 - m12) / s;
  1376. result.x = (m13 + m31) / s;
  1377. result.y = (m23 + m32) / s;
  1378. result.z = 0.25 * s;
  1379. }
  1380. };
  1381. Quaternion.Inverse = function (q) {
  1382. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1383. };
  1384. Quaternion.Identity = function () {
  1385. return new Quaternion(0, 0, 0, 1);
  1386. };
  1387. Quaternion.RotationAxis = function (axis, angle) {
  1388. var result = new Quaternion();
  1389. var sin = Math.sin(angle / 2);
  1390. axis.normalize();
  1391. result.w = Math.cos(angle / 2);
  1392. result.x = axis.x * sin;
  1393. result.y = axis.y * sin;
  1394. result.z = axis.z * sin;
  1395. return result;
  1396. };
  1397. Quaternion.FromArray = function (array, offset) {
  1398. if (!offset) {
  1399. offset = 0;
  1400. }
  1401. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1402. };
  1403. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1404. var result = new Quaternion();
  1405. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1406. return result;
  1407. };
  1408. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1409. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1410. var halfRoll = roll * 0.5;
  1411. var halfPitch = pitch * 0.5;
  1412. var halfYaw = yaw * 0.5;
  1413. var sinRoll = Math.sin(halfRoll);
  1414. var cosRoll = Math.cos(halfRoll);
  1415. var sinPitch = Math.sin(halfPitch);
  1416. var cosPitch = Math.cos(halfPitch);
  1417. var sinYaw = Math.sin(halfYaw);
  1418. var cosYaw = Math.cos(halfYaw);
  1419. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1420. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1421. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1422. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1423. };
  1424. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1425. var result = new Quaternion();
  1426. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1427. return result;
  1428. };
  1429. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1430. // Produces a quaternion from Euler angles in the z-x-z orientation
  1431. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1432. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1433. var halfBeta = beta * 0.5;
  1434. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1435. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1436. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1437. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1438. };
  1439. Quaternion.Slerp = function (left, right, amount) {
  1440. var num2;
  1441. var num3;
  1442. var num = amount;
  1443. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1444. var flag = false;
  1445. if (num4 < 0) {
  1446. flag = true;
  1447. num4 = -num4;
  1448. }
  1449. if (num4 > 0.999999) {
  1450. num3 = 1 - num;
  1451. num2 = flag ? -num : num;
  1452. }
  1453. else {
  1454. var num5 = Math.acos(num4);
  1455. var num6 = (1.0 / Math.sin(num5));
  1456. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1457. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1458. }
  1459. 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));
  1460. };
  1461. return Quaternion;
  1462. })();
  1463. BABYLON.Quaternion = Quaternion;
  1464. var Matrix = (function () {
  1465. function Matrix() {
  1466. this.m = new Float32Array(16);
  1467. }
  1468. // Properties
  1469. Matrix.prototype.isIdentity = function () {
  1470. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1471. return false;
  1472. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1473. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1474. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1475. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1476. return false;
  1477. return true;
  1478. };
  1479. Matrix.prototype.determinant = function () {
  1480. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1481. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1482. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1483. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1484. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1485. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1486. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1487. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1488. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1489. };
  1490. // Methods
  1491. Matrix.prototype.toArray = function () {
  1492. return this.m;
  1493. };
  1494. Matrix.prototype.asArray = function () {
  1495. return this.toArray();
  1496. };
  1497. Matrix.prototype.invert = function () {
  1498. this.invertToRef(this);
  1499. return this;
  1500. };
  1501. Matrix.prototype.reset = function () {
  1502. for (var index = 0; index < 16; index++) {
  1503. this.m[index] = 0;
  1504. }
  1505. return this;
  1506. };
  1507. Matrix.prototype.add = function (other) {
  1508. var result = new Matrix();
  1509. this.addToRef(other, result);
  1510. return result;
  1511. };
  1512. Matrix.prototype.addToRef = function (other, result) {
  1513. for (var index = 0; index < 16; index++) {
  1514. result.m[index] = this.m[index] + other.m[index];
  1515. }
  1516. return this;
  1517. };
  1518. Matrix.prototype.addToSelf = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] += other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.invertToRef = function (other) {
  1525. var l1 = this.m[0];
  1526. var l2 = this.m[1];
  1527. var l3 = this.m[2];
  1528. var l4 = this.m[3];
  1529. var l5 = this.m[4];
  1530. var l6 = this.m[5];
  1531. var l7 = this.m[6];
  1532. var l8 = this.m[7];
  1533. var l9 = this.m[8];
  1534. var l10 = this.m[9];
  1535. var l11 = this.m[10];
  1536. var l12 = this.m[11];
  1537. var l13 = this.m[12];
  1538. var l14 = this.m[13];
  1539. var l15 = this.m[14];
  1540. var l16 = this.m[15];
  1541. var l17 = (l11 * l16) - (l12 * l15);
  1542. var l18 = (l10 * l16) - (l12 * l14);
  1543. var l19 = (l10 * l15) - (l11 * l14);
  1544. var l20 = (l9 * l16) - (l12 * l13);
  1545. var l21 = (l9 * l15) - (l11 * l13);
  1546. var l22 = (l9 * l14) - (l10 * l13);
  1547. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1548. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1549. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1550. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1551. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1552. var l28 = (l7 * l16) - (l8 * l15);
  1553. var l29 = (l6 * l16) - (l8 * l14);
  1554. var l30 = (l6 * l15) - (l7 * l14);
  1555. var l31 = (l5 * l16) - (l8 * l13);
  1556. var l32 = (l5 * l15) - (l7 * l13);
  1557. var l33 = (l5 * l14) - (l6 * l13);
  1558. var l34 = (l7 * l12) - (l8 * l11);
  1559. var l35 = (l6 * l12) - (l8 * l10);
  1560. var l36 = (l6 * l11) - (l7 * l10);
  1561. var l37 = (l5 * l12) - (l8 * l9);
  1562. var l38 = (l5 * l11) - (l7 * l9);
  1563. var l39 = (l5 * l10) - (l6 * l9);
  1564. other.m[0] = l23 * l27;
  1565. other.m[4] = l24 * l27;
  1566. other.m[8] = l25 * l27;
  1567. other.m[12] = l26 * l27;
  1568. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1569. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1570. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1571. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1572. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1573. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1574. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1575. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1576. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1577. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1578. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1579. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1580. return this;
  1581. };
  1582. Matrix.prototype.setTranslation = function (vector3) {
  1583. this.m[12] = vector3.x;
  1584. this.m[13] = vector3.y;
  1585. this.m[14] = vector3.z;
  1586. return this;
  1587. };
  1588. Matrix.prototype.multiply = function (other) {
  1589. var result = new Matrix();
  1590. this.multiplyToRef(other, result);
  1591. return result;
  1592. };
  1593. Matrix.prototype.copyFrom = function (other) {
  1594. for (var index = 0; index < 16; index++) {
  1595. this.m[index] = other.m[index];
  1596. }
  1597. return this;
  1598. };
  1599. Matrix.prototype.copyToArray = function (array, offset) {
  1600. if (offset === void 0) { offset = 0; }
  1601. for (var index = 0; index < 16; index++) {
  1602. array[offset + index] = this.m[index];
  1603. }
  1604. return this;
  1605. };
  1606. Matrix.prototype.multiplyToRef = function (other, result) {
  1607. this.multiplyToArray(other, result.m, 0);
  1608. return this;
  1609. };
  1610. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1611. var tm0 = this.m[0];
  1612. var tm1 = this.m[1];
  1613. var tm2 = this.m[2];
  1614. var tm3 = this.m[3];
  1615. var tm4 = this.m[4];
  1616. var tm5 = this.m[5];
  1617. var tm6 = this.m[6];
  1618. var tm7 = this.m[7];
  1619. var tm8 = this.m[8];
  1620. var tm9 = this.m[9];
  1621. var tm10 = this.m[10];
  1622. var tm11 = this.m[11];
  1623. var tm12 = this.m[12];
  1624. var tm13 = this.m[13];
  1625. var tm14 = this.m[14];
  1626. var tm15 = this.m[15];
  1627. var om0 = other.m[0];
  1628. var om1 = other.m[1];
  1629. var om2 = other.m[2];
  1630. var om3 = other.m[3];
  1631. var om4 = other.m[4];
  1632. var om5 = other.m[5];
  1633. var om6 = other.m[6];
  1634. var om7 = other.m[7];
  1635. var om8 = other.m[8];
  1636. var om9 = other.m[9];
  1637. var om10 = other.m[10];
  1638. var om11 = other.m[11];
  1639. var om12 = other.m[12];
  1640. var om13 = other.m[13];
  1641. var om14 = other.m[14];
  1642. var om15 = other.m[15];
  1643. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1644. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1645. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1646. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1647. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1648. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1649. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1650. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1651. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1652. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1653. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1654. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1655. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1656. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1657. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1658. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1659. return this;
  1660. };
  1661. Matrix.prototype.equals = function (value) {
  1662. return value &&
  1663. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1664. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1665. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1666. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1667. };
  1668. Matrix.prototype.clone = function () {
  1669. 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]);
  1670. };
  1671. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1672. translation.x = this.m[12];
  1673. translation.y = this.m[13];
  1674. translation.z = this.m[14];
  1675. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1676. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1677. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1678. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1679. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1680. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1681. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1682. rotation.x = 0;
  1683. rotation.y = 0;
  1684. rotation.z = 0;
  1685. rotation.w = 1;
  1686. return false;
  1687. }
  1688. 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);
  1689. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1690. return true;
  1691. };
  1692. // Statics
  1693. Matrix.FromArray = function (array, offset) {
  1694. var result = new Matrix();
  1695. if (!offset) {
  1696. offset = 0;
  1697. }
  1698. Matrix.FromArrayToRef(array, offset, result);
  1699. return result;
  1700. };
  1701. Matrix.FromArrayToRef = function (array, offset, result) {
  1702. for (var index = 0; index < 16; index++) {
  1703. result.m[index] = array[index + offset];
  1704. }
  1705. };
  1706. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1707. for (var index = 0; index < 16; index++) {
  1708. result.m[index] = array[index + offset] * scale;
  1709. }
  1710. };
  1711. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1712. result.m[0] = initialM11;
  1713. result.m[1] = initialM12;
  1714. result.m[2] = initialM13;
  1715. result.m[3] = initialM14;
  1716. result.m[4] = initialM21;
  1717. result.m[5] = initialM22;
  1718. result.m[6] = initialM23;
  1719. result.m[7] = initialM24;
  1720. result.m[8] = initialM31;
  1721. result.m[9] = initialM32;
  1722. result.m[10] = initialM33;
  1723. result.m[11] = initialM34;
  1724. result.m[12] = initialM41;
  1725. result.m[13] = initialM42;
  1726. result.m[14] = initialM43;
  1727. result.m[15] = initialM44;
  1728. };
  1729. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1730. var result = new Matrix();
  1731. result.m[0] = initialM11;
  1732. result.m[1] = initialM12;
  1733. result.m[2] = initialM13;
  1734. result.m[3] = initialM14;
  1735. result.m[4] = initialM21;
  1736. result.m[5] = initialM22;
  1737. result.m[6] = initialM23;
  1738. result.m[7] = initialM24;
  1739. result.m[8] = initialM31;
  1740. result.m[9] = initialM32;
  1741. result.m[10] = initialM33;
  1742. result.m[11] = initialM34;
  1743. result.m[12] = initialM41;
  1744. result.m[13] = initialM42;
  1745. result.m[14] = initialM43;
  1746. result.m[15] = initialM44;
  1747. return result;
  1748. };
  1749. Matrix.Compose = function (scale, rotation, translation) {
  1750. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1751. var rotationMatrix = Matrix.Identity();
  1752. rotation.toRotationMatrix(rotationMatrix);
  1753. result = result.multiply(rotationMatrix);
  1754. result.setTranslation(translation);
  1755. return result;
  1756. };
  1757. Matrix.Identity = function () {
  1758. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1759. };
  1760. Matrix.IdentityToRef = function (result) {
  1761. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1762. };
  1763. Matrix.Zero = function () {
  1764. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1765. };
  1766. Matrix.RotationX = function (angle) {
  1767. var result = new Matrix();
  1768. Matrix.RotationXToRef(angle, result);
  1769. return result;
  1770. };
  1771. Matrix.Invert = function (source) {
  1772. var result = new Matrix();
  1773. source.invertToRef(result);
  1774. return result;
  1775. };
  1776. Matrix.RotationXToRef = function (angle, result) {
  1777. var s = Math.sin(angle);
  1778. var c = Math.cos(angle);
  1779. result.m[0] = 1.0;
  1780. result.m[15] = 1.0;
  1781. result.m[5] = c;
  1782. result.m[10] = c;
  1783. result.m[9] = -s;
  1784. result.m[6] = s;
  1785. result.m[1] = 0;
  1786. result.m[2] = 0;
  1787. result.m[3] = 0;
  1788. result.m[4] = 0;
  1789. result.m[7] = 0;
  1790. result.m[8] = 0;
  1791. result.m[11] = 0;
  1792. result.m[12] = 0;
  1793. result.m[13] = 0;
  1794. result.m[14] = 0;
  1795. };
  1796. Matrix.RotationY = function (angle) {
  1797. var result = new Matrix();
  1798. Matrix.RotationYToRef(angle, result);
  1799. return result;
  1800. };
  1801. Matrix.RotationYToRef = function (angle, result) {
  1802. var s = Math.sin(angle);
  1803. var c = Math.cos(angle);
  1804. result.m[5] = 1.0;
  1805. result.m[15] = 1.0;
  1806. result.m[0] = c;
  1807. result.m[2] = -s;
  1808. result.m[8] = s;
  1809. result.m[10] = c;
  1810. result.m[1] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[6] = 0;
  1814. result.m[7] = 0;
  1815. result.m[9] = 0;
  1816. result.m[11] = 0;
  1817. result.m[12] = 0;
  1818. result.m[13] = 0;
  1819. result.m[14] = 0;
  1820. };
  1821. Matrix.RotationZ = function (angle) {
  1822. var result = new Matrix();
  1823. Matrix.RotationZToRef(angle, result);
  1824. return result;
  1825. };
  1826. Matrix.RotationZToRef = function (angle, result) {
  1827. var s = Math.sin(angle);
  1828. var c = Math.cos(angle);
  1829. result.m[10] = 1.0;
  1830. result.m[15] = 1.0;
  1831. result.m[0] = c;
  1832. result.m[1] = s;
  1833. result.m[4] = -s;
  1834. result.m[5] = c;
  1835. result.m[2] = 0;
  1836. result.m[3] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[8] = 0;
  1840. result.m[9] = 0;
  1841. result.m[11] = 0;
  1842. result.m[12] = 0;
  1843. result.m[13] = 0;
  1844. result.m[14] = 0;
  1845. };
  1846. Matrix.RotationAxis = function (axis, angle) {
  1847. var result = Matrix.Zero();
  1848. Matrix.RotationAxisToRef(axis, angle, result);
  1849. return result;
  1850. };
  1851. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1852. var s = Math.sin(-angle);
  1853. var c = Math.cos(-angle);
  1854. var c1 = 1 - c;
  1855. axis.normalize();
  1856. result.m[0] = (axis.x * axis.x) * c1 + c;
  1857. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1858. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1859. result.m[3] = 0.0;
  1860. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1861. result.m[5] = (axis.y * axis.y) * c1 + c;
  1862. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1863. result.m[7] = 0.0;
  1864. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1865. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1866. result.m[10] = (axis.z * axis.z) * c1 + c;
  1867. result.m[11] = 0.0;
  1868. result.m[15] = 1.0;
  1869. };
  1870. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1871. var result = new Matrix();
  1872. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1876. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1877. this._tempQuaternion.toRotationMatrix(result);
  1878. };
  1879. Matrix.Scaling = function (x, y, z) {
  1880. var result = Matrix.Zero();
  1881. Matrix.ScalingToRef(x, y, z, result);
  1882. return result;
  1883. };
  1884. Matrix.ScalingToRef = function (x, y, z, result) {
  1885. result.m[0] = x;
  1886. result.m[1] = 0;
  1887. result.m[2] = 0;
  1888. result.m[3] = 0;
  1889. result.m[4] = 0;
  1890. result.m[5] = y;
  1891. result.m[6] = 0;
  1892. result.m[7] = 0;
  1893. result.m[8] = 0;
  1894. result.m[9] = 0;
  1895. result.m[10] = z;
  1896. result.m[11] = 0;
  1897. result.m[12] = 0;
  1898. result.m[13] = 0;
  1899. result.m[14] = 0;
  1900. result.m[15] = 1.0;
  1901. };
  1902. Matrix.Translation = function (x, y, z) {
  1903. var result = Matrix.Identity();
  1904. Matrix.TranslationToRef(x, y, z, result);
  1905. return result;
  1906. };
  1907. Matrix.TranslationToRef = function (x, y, z, result) {
  1908. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1909. };
  1910. Matrix.LookAtLH = function (eye, target, up) {
  1911. var result = Matrix.Zero();
  1912. Matrix.LookAtLHToRef(eye, target, up, result);
  1913. return result;
  1914. };
  1915. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1916. // Z axis
  1917. target.subtractToRef(eye, this._zAxis);
  1918. this._zAxis.normalize();
  1919. // X axis
  1920. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1921. if (this._xAxis.lengthSquared() === 0) {
  1922. this._xAxis.x = 1.0;
  1923. }
  1924. else {
  1925. this._xAxis.normalize();
  1926. }
  1927. // Y axis
  1928. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1929. this._yAxis.normalize();
  1930. // Eye angles
  1931. var ex = -Vector3.Dot(this._xAxis, eye);
  1932. var ey = -Vector3.Dot(this._yAxis, eye);
  1933. var ez = -Vector3.Dot(this._zAxis, eye);
  1934. 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);
  1935. };
  1936. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1937. var matrix = Matrix.Zero();
  1938. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1939. return matrix;
  1940. };
  1941. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1942. var hw = 2.0 / width;
  1943. var hh = 2.0 / height;
  1944. var id = 1.0 / (zfar - znear);
  1945. var nid = znear / (znear - zfar);
  1946. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1947. };
  1948. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1949. var matrix = Matrix.Zero();
  1950. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1951. return matrix;
  1952. };
  1953. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1954. result.m[0] = 2.0 / (right - left);
  1955. result.m[1] = result.m[2] = result.m[3] = 0;
  1956. result.m[5] = 2.0 / (top - bottom);
  1957. result.m[4] = result.m[6] = result.m[7] = 0;
  1958. result.m[10] = -1.0 / (znear - zfar);
  1959. result.m[8] = result.m[9] = result.m[11] = 0;
  1960. result.m[12] = (left + right) / (left - right);
  1961. result.m[13] = (top + bottom) / (bottom - top);
  1962. result.m[14] = znear / (znear - zfar);
  1963. result.m[15] = 1.0;
  1964. };
  1965. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1966. var matrix = Matrix.Zero();
  1967. matrix.m[0] = (2.0 * znear) / width;
  1968. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1969. matrix.m[5] = (2.0 * znear) / height;
  1970. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1971. matrix.m[10] = -zfar / (znear - zfar);
  1972. matrix.m[8] = matrix.m[9] = 0.0;
  1973. matrix.m[11] = 1.0;
  1974. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1975. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1976. return matrix;
  1977. };
  1978. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1979. var matrix = Matrix.Zero();
  1980. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1981. return matrix;
  1982. };
  1983. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1984. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1985. var tan = 1.0 / (Math.tan(fov * 0.5));
  1986. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1987. if (v_fixed) {
  1988. result.m[0] = tan / aspect;
  1989. }
  1990. else {
  1991. result.m[0] = tan;
  1992. }
  1993. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1994. if (v_fixed) {
  1995. result.m[5] = tan;
  1996. }
  1997. else {
  1998. result.m[5] = tan * aspect;
  1999. }
  2000. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2001. result.m[8] = result.m[9] = 0.0;
  2002. result.m[10] = -zfar / (znear - zfar);
  2003. result.m[11] = 1.0;
  2004. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2005. result.m[14] = (znear * zfar) / (znear - zfar);
  2006. };
  2007. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2008. var cw = viewport.width;
  2009. var ch = viewport.height;
  2010. var cx = viewport.x;
  2011. var cy = viewport.y;
  2012. 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);
  2013. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2014. };
  2015. Matrix.GetAsMatrix2x2 = function (matrix) {
  2016. return new Float32Array([
  2017. matrix.m[0], matrix.m[1],
  2018. matrix.m[4], matrix.m[5]
  2019. ]);
  2020. };
  2021. Matrix.GetAsMatrix3x3 = function (matrix) {
  2022. return new Float32Array([
  2023. matrix.m[0], matrix.m[1], matrix.m[2],
  2024. matrix.m[4], matrix.m[5], matrix.m[6],
  2025. matrix.m[8], matrix.m[9], matrix.m[10]
  2026. ]);
  2027. };
  2028. Matrix.Transpose = function (matrix) {
  2029. var result = new Matrix();
  2030. result.m[0] = matrix.m[0];
  2031. result.m[1] = matrix.m[4];
  2032. result.m[2] = matrix.m[8];
  2033. result.m[3] = matrix.m[12];
  2034. result.m[4] = matrix.m[1];
  2035. result.m[5] = matrix.m[5];
  2036. result.m[6] = matrix.m[9];
  2037. result.m[7] = matrix.m[13];
  2038. result.m[8] = matrix.m[2];
  2039. result.m[9] = matrix.m[6];
  2040. result.m[10] = matrix.m[10];
  2041. result.m[11] = matrix.m[14];
  2042. result.m[12] = matrix.m[3];
  2043. result.m[13] = matrix.m[7];
  2044. result.m[14] = matrix.m[11];
  2045. result.m[15] = matrix.m[15];
  2046. return result;
  2047. };
  2048. Matrix.Reflection = function (plane) {
  2049. var matrix = new Matrix();
  2050. Matrix.ReflectionToRef(plane, matrix);
  2051. return matrix;
  2052. };
  2053. Matrix.ReflectionToRef = function (plane, result) {
  2054. plane.normalize();
  2055. var x = plane.normal.x;
  2056. var y = plane.normal.y;
  2057. var z = plane.normal.z;
  2058. var temp = -2 * x;
  2059. var temp2 = -2 * y;
  2060. var temp3 = -2 * z;
  2061. result.m[0] = (temp * x) + 1;
  2062. result.m[1] = temp2 * x;
  2063. result.m[2] = temp3 * x;
  2064. result.m[3] = 0.0;
  2065. result.m[4] = temp * y;
  2066. result.m[5] = (temp2 * y) + 1;
  2067. result.m[6] = temp3 * y;
  2068. result.m[7] = 0.0;
  2069. result.m[8] = temp * z;
  2070. result.m[9] = temp2 * z;
  2071. result.m[10] = (temp3 * z) + 1;
  2072. result.m[11] = 0.0;
  2073. result.m[12] = temp * plane.d;
  2074. result.m[13] = temp2 * plane.d;
  2075. result.m[14] = temp3 * plane.d;
  2076. result.m[15] = 1.0;
  2077. };
  2078. Matrix._tempQuaternion = new Quaternion();
  2079. Matrix._xAxis = Vector3.Zero();
  2080. Matrix._yAxis = Vector3.Zero();
  2081. Matrix._zAxis = Vector3.Zero();
  2082. return Matrix;
  2083. })();
  2084. BABYLON.Matrix = Matrix;
  2085. var Plane = (function () {
  2086. function Plane(a, b, c, d) {
  2087. this.normal = new Vector3(a, b, c);
  2088. this.d = d;
  2089. }
  2090. Plane.prototype.asArray = function () {
  2091. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2092. };
  2093. // Methods
  2094. Plane.prototype.clone = function () {
  2095. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2096. };
  2097. Plane.prototype.normalize = function () {
  2098. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2099. var magnitude = 0;
  2100. if (norm !== 0) {
  2101. magnitude = 1.0 / norm;
  2102. }
  2103. this.normal.x *= magnitude;
  2104. this.normal.y *= magnitude;
  2105. this.normal.z *= magnitude;
  2106. this.d *= magnitude;
  2107. return this;
  2108. };
  2109. Plane.prototype.transform = function (transformation) {
  2110. var transposedMatrix = Matrix.Transpose(transformation);
  2111. var x = this.normal.x;
  2112. var y = this.normal.y;
  2113. var z = this.normal.z;
  2114. var d = this.d;
  2115. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2116. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2117. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2118. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2119. return new Plane(normalX, normalY, normalZ, finalD);
  2120. };
  2121. Plane.prototype.dotCoordinate = function (point) {
  2122. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2123. };
  2124. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2125. var x1 = point2.x - point1.x;
  2126. var y1 = point2.y - point1.y;
  2127. var z1 = point2.z - point1.z;
  2128. var x2 = point3.x - point1.x;
  2129. var y2 = point3.y - point1.y;
  2130. var z2 = point3.z - point1.z;
  2131. var yz = (y1 * z2) - (z1 * y2);
  2132. var xz = (z1 * x2) - (x1 * z2);
  2133. var xy = (x1 * y2) - (y1 * x2);
  2134. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2135. var invPyth;
  2136. if (pyth !== 0) {
  2137. invPyth = 1.0 / pyth;
  2138. }
  2139. else {
  2140. invPyth = 0;
  2141. }
  2142. this.normal.x = yz * invPyth;
  2143. this.normal.y = xz * invPyth;
  2144. this.normal.z = xy * invPyth;
  2145. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2146. return this;
  2147. };
  2148. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2149. var dot = Vector3.Dot(this.normal, direction);
  2150. return (dot <= epsilon);
  2151. };
  2152. Plane.prototype.signedDistanceTo = function (point) {
  2153. return Vector3.Dot(point, this.normal) + this.d;
  2154. };
  2155. // Statics
  2156. Plane.FromArray = function (array) {
  2157. return new Plane(array[0], array[1], array[2], array[3]);
  2158. };
  2159. Plane.FromPoints = function (point1, point2, point3) {
  2160. var result = new Plane(0, 0, 0, 0);
  2161. result.copyFromPoints(point1, point2, point3);
  2162. return result;
  2163. };
  2164. Plane.FromPositionAndNormal = function (origin, normal) {
  2165. var result = new Plane(0, 0, 0, 0);
  2166. normal.normalize();
  2167. result.normal = normal;
  2168. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2169. return result;
  2170. };
  2171. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2172. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2173. return Vector3.Dot(point, normal) + d;
  2174. };
  2175. return Plane;
  2176. })();
  2177. BABYLON.Plane = Plane;
  2178. var Viewport = (function () {
  2179. function Viewport(x, y, width, height) {
  2180. this.x = x;
  2181. this.y = y;
  2182. this.width = width;
  2183. this.height = height;
  2184. }
  2185. Viewport.prototype.toGlobal = function (engine) {
  2186. var width = engine.getRenderWidth();
  2187. var height = engine.getRenderHeight();
  2188. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2189. };
  2190. return Viewport;
  2191. })();
  2192. BABYLON.Viewport = Viewport;
  2193. var Frustum = (function () {
  2194. function Frustum() {
  2195. }
  2196. Frustum.GetPlanes = function (transform) {
  2197. var frustumPlanes = [];
  2198. for (var index = 0; index < 6; index++) {
  2199. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2200. }
  2201. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2202. return frustumPlanes;
  2203. };
  2204. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2205. // Near
  2206. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2207. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2208. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2209. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2210. frustumPlanes[0].normalize();
  2211. // Far
  2212. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2213. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2214. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2215. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2216. frustumPlanes[1].normalize();
  2217. // Left
  2218. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2219. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2220. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2221. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2222. frustumPlanes[2].normalize();
  2223. // Right
  2224. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2225. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2226. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2227. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2228. frustumPlanes[3].normalize();
  2229. // Top
  2230. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2231. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2232. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2233. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2234. frustumPlanes[4].normalize();
  2235. // Bottom
  2236. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2237. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2238. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2239. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2240. frustumPlanes[5].normalize();
  2241. };
  2242. return Frustum;
  2243. })();
  2244. BABYLON.Frustum = Frustum;
  2245. var Ray = (function () {
  2246. function Ray(origin, direction, length) {
  2247. if (length === void 0) { length = Number.MAX_VALUE; }
  2248. this.origin = origin;
  2249. this.direction = direction;
  2250. this.length = length;
  2251. }
  2252. // Methods
  2253. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2254. var d = 0.0;
  2255. var maxValue = Number.MAX_VALUE;
  2256. var inv;
  2257. var min;
  2258. var max;
  2259. var temp;
  2260. if (Math.abs(this.direction.x) < 0.0000001) {
  2261. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2262. return false;
  2263. }
  2264. }
  2265. else {
  2266. inv = 1.0 / this.direction.x;
  2267. min = (minimum.x - this.origin.x) * inv;
  2268. max = (maximum.x - this.origin.x) * inv;
  2269. if (max === -Infinity) {
  2270. max = Infinity;
  2271. }
  2272. if (min > max) {
  2273. temp = min;
  2274. min = max;
  2275. max = temp;
  2276. }
  2277. d = Math.max(min, d);
  2278. maxValue = Math.min(max, maxValue);
  2279. if (d > maxValue) {
  2280. return false;
  2281. }
  2282. }
  2283. if (Math.abs(this.direction.y) < 0.0000001) {
  2284. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2285. return false;
  2286. }
  2287. }
  2288. else {
  2289. inv = 1.0 / this.direction.y;
  2290. min = (minimum.y - this.origin.y) * inv;
  2291. max = (maximum.y - this.origin.y) * inv;
  2292. if (max === -Infinity) {
  2293. max = Infinity;
  2294. }
  2295. if (min > max) {
  2296. temp = min;
  2297. min = max;
  2298. max = temp;
  2299. }
  2300. d = Math.max(min, d);
  2301. maxValue = Math.min(max, maxValue);
  2302. if (d > maxValue) {
  2303. return false;
  2304. }
  2305. }
  2306. if (Math.abs(this.direction.z) < 0.0000001) {
  2307. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2308. return false;
  2309. }
  2310. }
  2311. else {
  2312. inv = 1.0 / this.direction.z;
  2313. min = (minimum.z - this.origin.z) * inv;
  2314. max = (maximum.z - this.origin.z) * inv;
  2315. if (max === -Infinity) {
  2316. max = Infinity;
  2317. }
  2318. if (min > max) {
  2319. temp = min;
  2320. min = max;
  2321. max = temp;
  2322. }
  2323. d = Math.max(min, d);
  2324. maxValue = Math.min(max, maxValue);
  2325. if (d > maxValue) {
  2326. return false;
  2327. }
  2328. }
  2329. return true;
  2330. };
  2331. Ray.prototype.intersectsBox = function (box) {
  2332. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2333. };
  2334. Ray.prototype.intersectsSphere = function (sphere) {
  2335. var x = sphere.center.x - this.origin.x;
  2336. var y = sphere.center.y - this.origin.y;
  2337. var z = sphere.center.z - this.origin.z;
  2338. var pyth = (x * x) + (y * y) + (z * z);
  2339. var rr = sphere.radius * sphere.radius;
  2340. if (pyth <= rr) {
  2341. return true;
  2342. }
  2343. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2344. if (dot < 0.0) {
  2345. return false;
  2346. }
  2347. var temp = pyth - (dot * dot);
  2348. return temp <= rr;
  2349. };
  2350. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2351. if (!this._edge1) {
  2352. this._edge1 = Vector3.Zero();
  2353. this._edge2 = Vector3.Zero();
  2354. this._pvec = Vector3.Zero();
  2355. this._tvec = Vector3.Zero();
  2356. this._qvec = Vector3.Zero();
  2357. }
  2358. vertex1.subtractToRef(vertex0, this._edge1);
  2359. vertex2.subtractToRef(vertex0, this._edge2);
  2360. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2361. var det = Vector3.Dot(this._edge1, this._pvec);
  2362. if (det === 0) {
  2363. return null;
  2364. }
  2365. var invdet = 1 / det;
  2366. this.origin.subtractToRef(vertex0, this._tvec);
  2367. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2368. if (bu < 0 || bu > 1.0) {
  2369. return null;
  2370. }
  2371. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2372. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2373. if (bv < 0 || bu + bv > 1.0) {
  2374. return null;
  2375. }
  2376. //check if the distance is longer than the predefined length.
  2377. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2378. if (distance > this.length) {
  2379. return null;
  2380. }
  2381. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2382. };
  2383. // Statics
  2384. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2385. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2386. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2387. var direction = end.subtract(start);
  2388. direction.normalize();
  2389. return new Ray(start, direction);
  2390. };
  2391. /**
  2392. * 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
  2393. * transformed to the given world matrix.
  2394. * @param origin The origin point
  2395. * @param end The end point
  2396. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2397. */
  2398. Ray.CreateNewFromTo = function (origin, end, world) {
  2399. if (world === void 0) { world = Matrix.Identity(); }
  2400. var direction = end.subtract(origin);
  2401. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2402. direction.normalize();
  2403. return Ray.Transform(new Ray(origin, direction, length), world);
  2404. };
  2405. Ray.Transform = function (ray, matrix) {
  2406. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2407. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2408. return new Ray(newOrigin, newDirection, ray.length);
  2409. };
  2410. return Ray;
  2411. })();
  2412. BABYLON.Ray = Ray;
  2413. (function (Space) {
  2414. Space[Space["LOCAL"] = 0] = "LOCAL";
  2415. Space[Space["WORLD"] = 1] = "WORLD";
  2416. })(BABYLON.Space || (BABYLON.Space = {}));
  2417. var Space = BABYLON.Space;
  2418. var Axis = (function () {
  2419. function Axis() {
  2420. }
  2421. Axis.X = new Vector3(1, 0, 0);
  2422. Axis.Y = new Vector3(0, 1, 0);
  2423. Axis.Z = new Vector3(0, 0, 1);
  2424. return Axis;
  2425. })();
  2426. BABYLON.Axis = Axis;
  2427. ;
  2428. var BezierCurve = (function () {
  2429. function BezierCurve() {
  2430. }
  2431. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2432. // Extract X (which is equal to time here)
  2433. var f0 = 1 - 3 * x2 + 3 * x1;
  2434. var f1 = 3 * x2 - 6 * x1;
  2435. var f2 = 3 * x1;
  2436. var refinedT = t;
  2437. for (var i = 0; i < 5; i++) {
  2438. var refinedT2 = refinedT * refinedT;
  2439. var refinedT3 = refinedT2 * refinedT;
  2440. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2441. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2442. refinedT -= (x - t) * slope;
  2443. refinedT = Math.min(1, Math.max(0, refinedT));
  2444. }
  2445. // Resolve cubic bezier for the given x
  2446. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2447. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2448. Math.pow(refinedT, 3);
  2449. };
  2450. return BezierCurve;
  2451. })();
  2452. BABYLON.BezierCurve = BezierCurve;
  2453. (function (Orientation) {
  2454. Orientation[Orientation["CW"] = 0] = "CW";
  2455. Orientation[Orientation["CCW"] = 1] = "CCW";
  2456. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2457. var Orientation = BABYLON.Orientation;
  2458. var Angle = (function () {
  2459. function Angle(radians) {
  2460. var _this = this;
  2461. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2462. this.radians = function () { return _this._radians; };
  2463. this._radians = radians;
  2464. if (this._radians < 0)
  2465. this._radians += (2 * Math.PI);
  2466. }
  2467. Angle.BetweenTwoPoints = function (a, b) {
  2468. var delta = b.subtract(a);
  2469. var theta = Math.atan2(delta.y, delta.x);
  2470. return new Angle(theta);
  2471. };
  2472. Angle.FromRadians = function (radians) {
  2473. return new Angle(radians);
  2474. };
  2475. Angle.FromDegrees = function (degrees) {
  2476. return new Angle(degrees * Math.PI / 180);
  2477. };
  2478. return Angle;
  2479. })();
  2480. BABYLON.Angle = Angle;
  2481. var Arc2 = (function () {
  2482. function Arc2(startPoint, midPoint, endPoint) {
  2483. this.startPoint = startPoint;
  2484. this.midPoint = midPoint;
  2485. this.endPoint = endPoint;
  2486. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2487. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2488. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2489. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2490. 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);
  2491. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2492. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2493. var a1 = this.startAngle.degrees();
  2494. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2495. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2496. // angles correction
  2497. if (a2 - a1 > +180.0)
  2498. a2 -= 360.0;
  2499. if (a2 - a1 < -180.0)
  2500. a2 += 360.0;
  2501. if (a3 - a2 > +180.0)
  2502. a3 -= 360.0;
  2503. if (a3 - a2 < -180.0)
  2504. a3 += 360.0;
  2505. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2506. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2507. }
  2508. return Arc2;
  2509. })();
  2510. BABYLON.Arc2 = Arc2;
  2511. var PathCursor = (function () {
  2512. function PathCursor(path) {
  2513. this.path = path;
  2514. this._onchange = new Array();
  2515. this.value = 0;
  2516. this.animations = new Array();
  2517. }
  2518. PathCursor.prototype.getPoint = function () {
  2519. var point = this.path.getPointAtLengthPosition(this.value);
  2520. return new Vector3(point.x, 0, point.y);
  2521. };
  2522. PathCursor.prototype.moveAhead = function (step) {
  2523. if (step === void 0) { step = 0.002; }
  2524. this.move(step);
  2525. return this;
  2526. };
  2527. PathCursor.prototype.moveBack = function (step) {
  2528. if (step === void 0) { step = 0.002; }
  2529. this.move(-step);
  2530. return this;
  2531. };
  2532. PathCursor.prototype.move = function (step) {
  2533. if (Math.abs(step) > 1) {
  2534. throw "step size should be less than 1.";
  2535. }
  2536. this.value += step;
  2537. this.ensureLimits();
  2538. this.raiseOnChange();
  2539. return this;
  2540. };
  2541. PathCursor.prototype.ensureLimits = function () {
  2542. while (this.value > 1) {
  2543. this.value -= 1;
  2544. }
  2545. while (this.value < 0) {
  2546. this.value += 1;
  2547. }
  2548. return this;
  2549. };
  2550. // used by animation engine
  2551. PathCursor.prototype.markAsDirty = function (propertyName) {
  2552. this.ensureLimits();
  2553. this.raiseOnChange();
  2554. return this;
  2555. };
  2556. PathCursor.prototype.raiseOnChange = function () {
  2557. var _this = this;
  2558. this._onchange.forEach(function (f) { return f(_this); });
  2559. return this;
  2560. };
  2561. PathCursor.prototype.onchange = function (f) {
  2562. this._onchange.push(f);
  2563. return this;
  2564. };
  2565. return PathCursor;
  2566. })();
  2567. BABYLON.PathCursor = PathCursor;
  2568. var Path2 = (function () {
  2569. function Path2(x, y) {
  2570. this._points = new Array();
  2571. this._length = 0;
  2572. this.closed = false;
  2573. this._points.push(new Vector2(x, y));
  2574. }
  2575. Path2.prototype.addLineTo = function (x, y) {
  2576. if (closed) {
  2577. BABYLON.Tools.Error("cannot add lines to closed paths");
  2578. return this;
  2579. }
  2580. var newPoint = new Vector2(x, y);
  2581. var previousPoint = this._points[this._points.length - 1];
  2582. this._points.push(newPoint);
  2583. this._length += newPoint.subtract(previousPoint).length();
  2584. return this;
  2585. };
  2586. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2587. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2588. if (closed) {
  2589. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2590. return this;
  2591. }
  2592. var startPoint = this._points[this._points.length - 1];
  2593. var midPoint = new Vector2(midX, midY);
  2594. var endPoint = new Vector2(endX, endY);
  2595. var arc = new Arc2(startPoint, midPoint, endPoint);
  2596. var increment = arc.angle.radians() / numberOfSegments;
  2597. if (arc.orientation === Orientation.CW)
  2598. increment *= -1;
  2599. var currentAngle = arc.startAngle.radians() + increment;
  2600. for (var i = 0; i < numberOfSegments; i++) {
  2601. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2602. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2603. this.addLineTo(x, y);
  2604. currentAngle += increment;
  2605. }
  2606. return this;
  2607. };
  2608. Path2.prototype.close = function () {
  2609. this.closed = true;
  2610. return this;
  2611. };
  2612. Path2.prototype.length = function () {
  2613. var result = this._length;
  2614. if (!this.closed) {
  2615. var lastPoint = this._points[this._points.length - 1];
  2616. var firstPoint = this._points[0];
  2617. result += (firstPoint.subtract(lastPoint).length());
  2618. }
  2619. return result;
  2620. };
  2621. Path2.prototype.getPoints = function () {
  2622. return this._points;
  2623. };
  2624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2626. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2627. return Vector2.Zero();
  2628. }
  2629. var lengthPosition = normalizedLengthPosition * this.length();
  2630. var previousOffset = 0;
  2631. for (var i = 0; i < this._points.length; i++) {
  2632. var j = (i + 1) % this._points.length;
  2633. var a = this._points[i];
  2634. var b = this._points[j];
  2635. var bToA = b.subtract(a);
  2636. var nextOffset = (bToA.length() + previousOffset);
  2637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2638. var dir = bToA.normalize();
  2639. var localOffset = lengthPosition - previousOffset;
  2640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2641. }
  2642. previousOffset = nextOffset;
  2643. }
  2644. BABYLON.Tools.Error("internal error");
  2645. return Vector2.Zero();
  2646. };
  2647. Path2.StartingAt = function (x, y) {
  2648. return new Path2(x, y);
  2649. };
  2650. return Path2;
  2651. })();
  2652. BABYLON.Path2 = Path2;
  2653. var Path3D = (function () {
  2654. /**
  2655. * new Path3D(path, normal, raw)
  2656. * path : an array of Vector3, the curve axis of the Path3D
  2657. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2658. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2659. */
  2660. function Path3D(path, firstNormal, raw) {
  2661. this.path = path;
  2662. this._curve = new Array();
  2663. this._distances = new Array();
  2664. this._tangents = new Array();
  2665. this._normals = new Array();
  2666. this._binormals = new Array();
  2667. for (var p = 0; p < path.length; p++) {
  2668. this._curve[p] = path[p].clone(); // hard copy
  2669. }
  2670. this._raw = raw || false;
  2671. this._compute(firstNormal);
  2672. }
  2673. Path3D.prototype.getCurve = function () {
  2674. return this._curve;
  2675. };
  2676. Path3D.prototype.getTangents = function () {
  2677. return this._tangents;
  2678. };
  2679. Path3D.prototype.getNormals = function () {
  2680. return this._normals;
  2681. };
  2682. Path3D.prototype.getBinormals = function () {
  2683. return this._binormals;
  2684. };
  2685. Path3D.prototype.getDistances = function () {
  2686. return this._distances;
  2687. };
  2688. Path3D.prototype.update = function (path, firstNormal) {
  2689. for (var p = 0; p < path.length; p++) {
  2690. this._curve[p].x = path[p].x;
  2691. this._curve[p].y = path[p].y;
  2692. this._curve[p].z = path[p].z;
  2693. }
  2694. this._compute(firstNormal);
  2695. return this;
  2696. };
  2697. // private function compute() : computes tangents, normals and binormals
  2698. Path3D.prototype._compute = function (firstNormal) {
  2699. var l = this._curve.length;
  2700. // first and last tangents
  2701. this._tangents[0] = this._getFirstNonNullVector(0);
  2702. if (!this._raw) {
  2703. this._tangents[0].normalize();
  2704. }
  2705. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2706. if (!this._raw) {
  2707. this._tangents[l - 1].normalize();
  2708. }
  2709. // normals and binormals at first point : arbitrary vector with _normalVector()
  2710. var tg0 = this._tangents[0];
  2711. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2712. this._normals[0] = pp0;
  2713. if (!this._raw) {
  2714. this._normals[0].normalize();
  2715. }
  2716. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2717. if (!this._raw) {
  2718. this._binormals[0].normalize();
  2719. }
  2720. this._distances[0] = 0;
  2721. // normals and binormals : next points
  2722. var prev; // previous vector (segment)
  2723. var cur; // current vector (segment)
  2724. var curTang; // current tangent
  2725. // previous normal
  2726. var prevBinor; // previous binormal
  2727. for (var i = 1; i < l; i++) {
  2728. // tangents
  2729. prev = this._getLastNonNullVector(i);
  2730. if (i < l - 1) {
  2731. cur = this._getFirstNonNullVector(i);
  2732. this._tangents[i] = prev.add(cur);
  2733. this._tangents[i].normalize();
  2734. }
  2735. this._distances[i] = this._distances[i - 1] + prev.length();
  2736. // normals and binormals
  2737. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2738. curTang = this._tangents[i];
  2739. prevBinor = this._binormals[i - 1];
  2740. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2741. if (!this._raw) {
  2742. this._normals[i].normalize();
  2743. }
  2744. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2745. if (!this._raw) {
  2746. this._binormals[i].normalize();
  2747. }
  2748. }
  2749. };
  2750. // private function getFirstNonNullVector(index)
  2751. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2752. Path3D.prototype._getFirstNonNullVector = function (index) {
  2753. var i = 1;
  2754. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2755. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2756. i++;
  2757. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2758. }
  2759. return nNVector;
  2760. };
  2761. // private function getLastNonNullVector(index)
  2762. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2763. Path3D.prototype._getLastNonNullVector = function (index) {
  2764. var i = 1;
  2765. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2766. while (nLVector.length() === 0 && index > i + 1) {
  2767. i++;
  2768. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2769. }
  2770. return nLVector;
  2771. };
  2772. // private function normalVector(v0, vt, va) :
  2773. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2774. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2775. Path3D.prototype._normalVector = function (v0, vt, va) {
  2776. var normal0;
  2777. if (va === undefined || va === null) {
  2778. var point;
  2779. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2780. point = new Vector3(0, -1, 0);
  2781. }
  2782. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2783. point = new Vector3(1, 0, 0);
  2784. }
  2785. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2786. point = new Vector3(0, 0, 1);
  2787. }
  2788. normal0 = Vector3.Cross(vt, point);
  2789. }
  2790. else {
  2791. normal0 = Vector3.Cross(vt, va);
  2792. Vector3.CrossToRef(normal0, vt, normal0);
  2793. }
  2794. normal0.normalize();
  2795. return normal0;
  2796. };
  2797. return Path3D;
  2798. })();
  2799. BABYLON.Path3D = Path3D;
  2800. var Curve3 = (function () {
  2801. function Curve3(points) {
  2802. this._length = 0;
  2803. this._points = points;
  2804. this._length = this._computeLength(points);
  2805. }
  2806. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2807. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2808. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2809. var bez = new Array();
  2810. var equation = function (t, val0, val1, val2) {
  2811. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2812. return res;
  2813. };
  2814. for (var i = 0; i <= nbPoints; i++) {
  2815. 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)));
  2816. }
  2817. return new Curve3(bez);
  2818. };
  2819. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2820. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2821. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2822. var bez = new Array();
  2823. var equation = function (t, val0, val1, val2, val3) {
  2824. 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;
  2825. return res;
  2826. };
  2827. for (var i = 0; i <= nbPoints; i++) {
  2828. 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)));
  2829. }
  2830. return new Curve3(bez);
  2831. };
  2832. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2833. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2834. var hermite = new Array();
  2835. var step = 1 / nbPoints;
  2836. for (var i = 0; i <= nbPoints; i++) {
  2837. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2838. }
  2839. return new Curve3(hermite);
  2840. };
  2841. Curve3.prototype.getPoints = function () {
  2842. return this._points;
  2843. };
  2844. Curve3.prototype.length = function () {
  2845. return this._length;
  2846. };
  2847. Curve3.prototype.continue = function (curve) {
  2848. var lastPoint = this._points[this._points.length - 1];
  2849. var continuedPoints = this._points.slice();
  2850. var curvePoints = curve.getPoints();
  2851. for (var i = 1; i < curvePoints.length; i++) {
  2852. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2853. }
  2854. var continuedCurve = new Curve3(continuedPoints);
  2855. return continuedCurve;
  2856. };
  2857. Curve3.prototype._computeLength = function (path) {
  2858. var l = 0;
  2859. for (var i = 1; i < path.length; i++) {
  2860. l += (path[i].subtract(path[i - 1])).length();
  2861. }
  2862. return l;
  2863. };
  2864. return Curve3;
  2865. })();
  2866. BABYLON.Curve3 = Curve3;
  2867. // Vertex formats
  2868. var PositionNormalVertex = (function () {
  2869. function PositionNormalVertex(position, normal) {
  2870. if (position === void 0) { position = Vector3.Zero(); }
  2871. if (normal === void 0) { normal = Vector3.Up(); }
  2872. this.position = position;
  2873. this.normal = normal;
  2874. }
  2875. PositionNormalVertex.prototype.clone = function () {
  2876. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2877. };
  2878. return PositionNormalVertex;
  2879. })();
  2880. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2881. var PositionNormalTextureVertex = (function () {
  2882. function PositionNormalTextureVertex(position, normal, uv) {
  2883. if (position === void 0) { position = Vector3.Zero(); }
  2884. if (normal === void 0) { normal = Vector3.Up(); }
  2885. if (uv === void 0) { uv = Vector2.Zero(); }
  2886. this.position = position;
  2887. this.normal = normal;
  2888. this.uv = uv;
  2889. }
  2890. PositionNormalTextureVertex.prototype.clone = function () {
  2891. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2892. };
  2893. return PositionNormalTextureVertex;
  2894. })();
  2895. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2896. })(BABYLON || (BABYLON = {}));
  2897. var BABYLON;
  2898. (function (BABYLON) {
  2899. var Database = (function () {
  2900. function Database(urlToScene, callbackManifestChecked) {
  2901. // Handling various flavors of prefixed version of IndexedDB
  2902. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2903. this.callbackManifestChecked = callbackManifestChecked;
  2904. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2905. this.db = null;
  2906. this.enableSceneOffline = false;
  2907. this.enableTexturesOffline = false;
  2908. this.manifestVersionFound = 0;
  2909. this.mustUpdateRessources = false;
  2910. this.hasReachedQuota = false;
  2911. if (!Database.IDBStorageEnabled) {
  2912. this.callbackManifestChecked(true);
  2913. }
  2914. else {
  2915. this.checkManifestFile();
  2916. }
  2917. }
  2918. Database.prototype.checkManifestFile = function () {
  2919. var _this = this;
  2920. function noManifestFile() {
  2921. that.enableSceneOffline = false;
  2922. that.enableTexturesOffline = false;
  2923. that.callbackManifestChecked(false);
  2924. }
  2925. var that = this;
  2926. var manifestURL = this.currentSceneUrl + ".manifest";
  2927. var xhr = new XMLHttpRequest();
  2928. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2929. xhr.open("GET", manifestURLTimeStamped, true);
  2930. xhr.addEventListener("load", function () {
  2931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2932. try {
  2933. var manifestFile = JSON.parse(xhr.response);
  2934. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2935. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2936. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2937. _this.manifestVersionFound = manifestFile.version;
  2938. }
  2939. if (_this.callbackManifestChecked) {
  2940. _this.callbackManifestChecked(true);
  2941. }
  2942. }
  2943. catch (ex) {
  2944. noManifestFile();
  2945. }
  2946. }
  2947. else {
  2948. noManifestFile();
  2949. }
  2950. }, false);
  2951. xhr.addEventListener("error", function (event) {
  2952. noManifestFile();
  2953. }, false);
  2954. try {
  2955. xhr.send();
  2956. }
  2957. catch (ex) {
  2958. BABYLON.Tools.Error("Error on XHR send request.");
  2959. that.callbackManifestChecked(false);
  2960. }
  2961. };
  2962. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2963. var _this = this;
  2964. function handleError() {
  2965. that.isSupported = false;
  2966. if (errorCallback)
  2967. errorCallback();
  2968. }
  2969. var that = this;
  2970. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2971. // Your browser doesn't support IndexedDB
  2972. this.isSupported = false;
  2973. if (errorCallback)
  2974. errorCallback();
  2975. }
  2976. else {
  2977. // If the DB hasn't been opened or created yet
  2978. if (!this.db) {
  2979. this.hasReachedQuota = false;
  2980. this.isSupported = true;
  2981. var request = this.idbFactory.open("babylonjs", 1);
  2982. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2983. request.onerror = function (event) {
  2984. handleError();
  2985. };
  2986. // executes when a version change transaction cannot complete due to other active transactions
  2987. request.onblocked = function (event) {
  2988. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2989. handleError();
  2990. };
  2991. // DB has been opened successfully
  2992. request.onsuccess = function (event) {
  2993. _this.db = request.result;
  2994. successCallback();
  2995. };
  2996. // Initialization of the DB. Creating Scenes & Textures stores
  2997. request.onupgradeneeded = function (event) {
  2998. _this.db = (event.target).result;
  2999. try {
  3000. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3001. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3002. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3003. }
  3004. catch (ex) {
  3005. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3006. handleError();
  3007. }
  3008. };
  3009. }
  3010. else {
  3011. if (successCallback)
  3012. successCallback();
  3013. }
  3014. }
  3015. };
  3016. Database.prototype.loadImageFromDB = function (url, image) {
  3017. var _this = this;
  3018. var completeURL = Database.ReturnFullUrlLocation(url);
  3019. var saveAndLoadImage = function () {
  3020. if (!_this.hasReachedQuota && _this.db !== null) {
  3021. // the texture is not yet in the DB, let's try to save it
  3022. _this._saveImageIntoDBAsync(completeURL, image);
  3023. }
  3024. else {
  3025. image.src = url;
  3026. }
  3027. };
  3028. if (!this.mustUpdateRessources) {
  3029. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3030. }
  3031. else {
  3032. saveAndLoadImage();
  3033. }
  3034. };
  3035. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3036. if (this.isSupported && this.db !== null) {
  3037. var texture;
  3038. var transaction = this.db.transaction(["textures"]);
  3039. transaction.onabort = function (event) {
  3040. image.src = url;
  3041. };
  3042. transaction.oncomplete = function (event) {
  3043. var blobTextureURL;
  3044. if (texture) {
  3045. var URL = window.URL || window.webkitURL;
  3046. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3047. image.onerror = function () {
  3048. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3049. image.src = url;
  3050. };
  3051. image.src = blobTextureURL;
  3052. }
  3053. else {
  3054. notInDBCallback();
  3055. }
  3056. };
  3057. var getRequest = transaction.objectStore("textures").get(url);
  3058. getRequest.onsuccess = function (event) {
  3059. texture = (event.target).result;
  3060. };
  3061. getRequest.onerror = function (event) {
  3062. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3063. image.src = url;
  3064. };
  3065. }
  3066. else {
  3067. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3068. image.src = url;
  3069. }
  3070. };
  3071. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3072. var _this = this;
  3073. if (this.isSupported) {
  3074. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3075. var generateBlobUrl = function () {
  3076. var blobTextureURL;
  3077. if (blob) {
  3078. var URL = window.URL || window.webkitURL;
  3079. try {
  3080. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3081. }
  3082. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3083. catch (ex) {
  3084. blobTextureURL = URL.createObjectURL(blob);
  3085. }
  3086. }
  3087. image.src = blobTextureURL;
  3088. };
  3089. if (Database.IsUASupportingBlobStorage) {
  3090. var xhr = new XMLHttpRequest(), blob;
  3091. xhr.open("GET", url, true);
  3092. xhr.responseType = "blob";
  3093. xhr.addEventListener("load", function () {
  3094. if (xhr.status === 200) {
  3095. // Blob as response (XHR2)
  3096. blob = xhr.response;
  3097. var transaction = _this.db.transaction(["textures"], "readwrite");
  3098. // the transaction could abort because of a QuotaExceededError error
  3099. transaction.onabort = function (event) {
  3100. try {
  3101. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3102. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3103. this.hasReachedQuota = true;
  3104. }
  3105. }
  3106. catch (ex) { }
  3107. generateBlobUrl();
  3108. };
  3109. transaction.oncomplete = function (event) {
  3110. generateBlobUrl();
  3111. };
  3112. var newTexture = { textureUrl: url, data: blob };
  3113. try {
  3114. // Put the blob into the dabase
  3115. var addRequest = transaction.objectStore("textures").put(newTexture);
  3116. addRequest.onsuccess = function (event) {
  3117. };
  3118. addRequest.onerror = function (event) {
  3119. generateBlobUrl();
  3120. };
  3121. }
  3122. catch (ex) {
  3123. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3124. if (ex.code === 25) {
  3125. Database.IsUASupportingBlobStorage = false;
  3126. }
  3127. image.src = url;
  3128. }
  3129. }
  3130. else {
  3131. image.src = url;
  3132. }
  3133. }, false);
  3134. xhr.addEventListener("error", function (event) {
  3135. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3136. image.src = url;
  3137. }, false);
  3138. xhr.send();
  3139. }
  3140. else {
  3141. image.src = url;
  3142. }
  3143. }
  3144. else {
  3145. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3146. image.src = url;
  3147. }
  3148. };
  3149. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3150. var _this = this;
  3151. var updateVersion = function (event) {
  3152. // the version is not yet in the DB or we need to update it
  3153. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3154. };
  3155. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3156. };
  3157. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3158. var _this = this;
  3159. if (this.isSupported) {
  3160. var version;
  3161. try {
  3162. var transaction = this.db.transaction(["versions"]);
  3163. transaction.oncomplete = function (event) {
  3164. if (version) {
  3165. // If the version in the JSON file is > than the version in DB
  3166. if (_this.manifestVersionFound > version.data) {
  3167. _this.mustUpdateRessources = true;
  3168. updateInDBCallback();
  3169. }
  3170. else {
  3171. callback(version.data);
  3172. }
  3173. }
  3174. else {
  3175. _this.mustUpdateRessources = true;
  3176. updateInDBCallback();
  3177. }
  3178. };
  3179. transaction.onabort = function (event) {
  3180. callback(-1);
  3181. };
  3182. var getRequest = transaction.objectStore("versions").get(url);
  3183. getRequest.onsuccess = function (event) {
  3184. version = (event.target).result;
  3185. };
  3186. getRequest.onerror = function (event) {
  3187. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3188. callback(-1);
  3189. };
  3190. }
  3191. catch (ex) {
  3192. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3193. callback(-1);
  3194. }
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. callback(-1);
  3199. }
  3200. };
  3201. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3202. var _this = this;
  3203. if (this.isSupported && !this.hasReachedQuota) {
  3204. try {
  3205. // Open a transaction to the database
  3206. var transaction = this.db.transaction(["versions"], "readwrite");
  3207. // the transaction could abort because of a QuotaExceededError error
  3208. transaction.onabort = function (event) {
  3209. try {
  3210. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3211. _this.hasReachedQuota = true;
  3212. }
  3213. }
  3214. catch (ex) { }
  3215. callback(-1);
  3216. };
  3217. transaction.oncomplete = function (event) {
  3218. callback(_this.manifestVersionFound);
  3219. };
  3220. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3221. // Put the scene into the database
  3222. var addRequest = transaction.objectStore("versions").put(newVersion);
  3223. addRequest.onsuccess = function (event) {
  3224. };
  3225. addRequest.onerror = function (event) {
  3226. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3227. };
  3228. }
  3229. catch (ex) {
  3230. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3231. callback(-1);
  3232. }
  3233. }
  3234. else {
  3235. callback(-1);
  3236. }
  3237. };
  3238. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3239. var _this = this;
  3240. var completeUrl = Database.ReturnFullUrlLocation(url);
  3241. var saveAndLoadFile = function (event) {
  3242. // the scene is not yet in the DB, let's try to save it
  3243. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3244. };
  3245. this._checkVersionFromDB(completeUrl, function (version) {
  3246. if (version !== -1) {
  3247. if (!_this.mustUpdateRessources) {
  3248. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3249. }
  3250. else {
  3251. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3252. }
  3253. }
  3254. else {
  3255. errorCallback();
  3256. }
  3257. });
  3258. };
  3259. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3260. if (this.isSupported) {
  3261. var targetStore;
  3262. if (url.indexOf(".babylon") !== -1) {
  3263. targetStore = "scenes";
  3264. }
  3265. else {
  3266. targetStore = "textures";
  3267. }
  3268. var file;
  3269. var transaction = this.db.transaction([targetStore]);
  3270. transaction.oncomplete = function (event) {
  3271. if (file) {
  3272. callback(file.data);
  3273. }
  3274. else {
  3275. notInDBCallback();
  3276. }
  3277. };
  3278. transaction.onabort = function (event) {
  3279. notInDBCallback();
  3280. };
  3281. var getRequest = transaction.objectStore(targetStore).get(url);
  3282. getRequest.onsuccess = function (event) {
  3283. file = (event.target).result;
  3284. };
  3285. getRequest.onerror = function (event) {
  3286. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3287. notInDBCallback();
  3288. };
  3289. }
  3290. else {
  3291. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3292. callback();
  3293. }
  3294. };
  3295. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3296. var _this = this;
  3297. if (this.isSupported) {
  3298. var targetStore;
  3299. if (url.indexOf(".babylon") !== -1) {
  3300. targetStore = "scenes";
  3301. }
  3302. else {
  3303. targetStore = "textures";
  3304. }
  3305. // Create XHR
  3306. var xhr = new XMLHttpRequest(), fileData;
  3307. xhr.open("GET", url, true);
  3308. if (useArrayBuffer) {
  3309. xhr.responseType = "arraybuffer";
  3310. }
  3311. xhr.onprogress = progressCallback;
  3312. xhr.addEventListener("load", function () {
  3313. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3314. // Blob as response (XHR2)
  3315. //fileData = xhr.responseText;
  3316. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3317. if (!_this.hasReachedQuota) {
  3318. // Open a transaction to the database
  3319. var transaction = _this.db.transaction([targetStore], "readwrite");
  3320. // the transaction could abort because of a QuotaExceededError error
  3321. transaction.onabort = function (event) {
  3322. try {
  3323. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3324. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3325. this.hasReachedQuota = true;
  3326. }
  3327. }
  3328. catch (ex) { }
  3329. callback(fileData);
  3330. };
  3331. transaction.oncomplete = function (event) {
  3332. callback(fileData);
  3333. };
  3334. var newFile;
  3335. if (targetStore === "scenes") {
  3336. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3337. }
  3338. else {
  3339. newFile = { textureUrl: url, data: fileData };
  3340. }
  3341. try {
  3342. // Put the scene into the database
  3343. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3344. addRequest.onsuccess = function (event) {
  3345. };
  3346. addRequest.onerror = function (event) {
  3347. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3348. };
  3349. }
  3350. catch (ex) {
  3351. callback(fileData);
  3352. }
  3353. }
  3354. else {
  3355. callback(fileData);
  3356. }
  3357. }
  3358. else {
  3359. callback();
  3360. }
  3361. }, false);
  3362. xhr.addEventListener("error", function (event) {
  3363. BABYLON.Tools.Error("error on XHR request.");
  3364. callback();
  3365. }, false);
  3366. xhr.send();
  3367. }
  3368. else {
  3369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3370. callback();
  3371. }
  3372. };
  3373. Database.IsUASupportingBlobStorage = true;
  3374. Database.IDBStorageEnabled = true;
  3375. Database.parseURL = function (url) {
  3376. var a = document.createElement('a');
  3377. a.href = url;
  3378. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3379. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3380. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3381. return absLocation;
  3382. };
  3383. Database.ReturnFullUrlLocation = function (url) {
  3384. if (url.indexOf("http:/") === -1) {
  3385. return (Database.parseURL(window.location.href) + url);
  3386. }
  3387. else {
  3388. return url;
  3389. }
  3390. };
  3391. return Database;
  3392. })();
  3393. BABYLON.Database = Database;
  3394. })(BABYLON || (BABYLON = {}));
  3395. var BABYLON;
  3396. (function (BABYLON) {
  3397. var Internals;
  3398. (function (Internals) {
  3399. /*
  3400. * Based on jsTGALoader - Javascript loader for TGA file
  3401. * By Vincent Thibault
  3402. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3403. */
  3404. var TGATools = (function () {
  3405. function TGATools() {
  3406. }
  3407. TGATools.GetTGAHeader = function (data) {
  3408. var offset = 0;
  3409. var header = {
  3410. id_length: data[offset++],
  3411. colormap_type: data[offset++],
  3412. image_type: data[offset++],
  3413. colormap_index: data[offset++] | data[offset++] << 8,
  3414. colormap_length: data[offset++] | data[offset++] << 8,
  3415. colormap_size: data[offset++],
  3416. origin: [
  3417. data[offset++] | data[offset++] << 8,
  3418. data[offset++] | data[offset++] << 8
  3419. ],
  3420. width: data[offset++] | data[offset++] << 8,
  3421. height: data[offset++] | data[offset++] << 8,
  3422. pixel_size: data[offset++],
  3423. flags: data[offset++]
  3424. };
  3425. return header;
  3426. };
  3427. TGATools.UploadContent = function (gl, data) {
  3428. // Not enough data to contain header ?
  3429. if (data.length < 19) {
  3430. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3431. return;
  3432. }
  3433. // Read Header
  3434. var offset = 18;
  3435. var header = TGATools.GetTGAHeader(data);
  3436. // Assume it's a valid Targa file.
  3437. if (header.id_length + offset > data.length) {
  3438. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3439. return;
  3440. }
  3441. // Skip not needed data
  3442. offset += header.id_length;
  3443. var use_rle = false;
  3444. var use_pal = false;
  3445. var use_rgb = false;
  3446. var use_grey = false;
  3447. // Get some informations.
  3448. switch (header.image_type) {
  3449. case TGATools._TYPE_RLE_INDEXED:
  3450. use_rle = true;
  3451. case TGATools._TYPE_INDEXED:
  3452. use_pal = true;
  3453. break;
  3454. case TGATools._TYPE_RLE_RGB:
  3455. use_rle = true;
  3456. case TGATools._TYPE_RGB:
  3457. use_rgb = true;
  3458. break;
  3459. case TGATools._TYPE_RLE_GREY:
  3460. use_rle = true;
  3461. case TGATools._TYPE_GREY:
  3462. use_grey = true;
  3463. break;
  3464. }
  3465. var pixel_data;
  3466. var numAlphaBits = header.flags & 0xf;
  3467. var pixel_size = header.pixel_size >> 3;
  3468. var pixel_total = header.width * header.height * pixel_size;
  3469. // Read palettes
  3470. var palettes;
  3471. if (use_pal) {
  3472. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3473. }
  3474. // Read LRE
  3475. if (use_rle) {
  3476. pixel_data = new Uint8Array(pixel_total);
  3477. var c, count, i;
  3478. var localOffset = 0;
  3479. var pixels = new Uint8Array(pixel_size);
  3480. while (offset < pixel_total && localOffset < pixel_total) {
  3481. c = data[offset++];
  3482. count = (c & 0x7f) + 1;
  3483. // RLE pixels
  3484. if (c & 0x80) {
  3485. // Bind pixel tmp array
  3486. for (i = 0; i < pixel_size; ++i) {
  3487. pixels[i] = data[offset++];
  3488. }
  3489. // Copy pixel array
  3490. for (i = 0; i < count; ++i) {
  3491. pixel_data.set(pixels, localOffset + i * pixel_size);
  3492. }
  3493. localOffset += pixel_size * count;
  3494. }
  3495. else {
  3496. count *= pixel_size;
  3497. for (i = 0; i < count; ++i) {
  3498. pixel_data[localOffset + i] = data[offset++];
  3499. }
  3500. localOffset += count;
  3501. }
  3502. }
  3503. }
  3504. else {
  3505. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3506. }
  3507. // Load to texture
  3508. var x_start, y_start, x_step, y_step, y_end, x_end;
  3509. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3510. default:
  3511. case TGATools._ORIGIN_UL:
  3512. x_start = 0;
  3513. x_step = 1;
  3514. x_end = header.width;
  3515. y_start = 0;
  3516. y_step = 1;
  3517. y_end = header.height;
  3518. break;
  3519. case TGATools._ORIGIN_BL:
  3520. x_start = 0;
  3521. x_step = 1;
  3522. x_end = header.width;
  3523. y_start = header.height - 1;
  3524. y_step = -1;
  3525. y_end = -1;
  3526. break;
  3527. case TGATools._ORIGIN_UR:
  3528. x_start = header.width - 1;
  3529. x_step = -1;
  3530. x_end = -1;
  3531. y_start = 0;
  3532. y_step = 1;
  3533. y_end = header.height;
  3534. break;
  3535. case TGATools._ORIGIN_BR:
  3536. x_start = header.width - 1;
  3537. x_step = -1;
  3538. x_end = -1;
  3539. y_start = header.height - 1;
  3540. y_step = -1;
  3541. y_end = -1;
  3542. break;
  3543. }
  3544. // Load the specify method
  3545. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3546. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3548. };
  3549. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3550. var image = pixel_data, colormap = palettes;
  3551. var width = header.width, height = header.height;
  3552. var color, i = 0, x, y;
  3553. var imageData = new Uint8Array(width * height * 4);
  3554. for (y = y_start; y !== y_end; y += y_step) {
  3555. for (x = x_start; x !== x_end; x += x_step, i++) {
  3556. color = image[i];
  3557. imageData[(x + width * y) * 4 + 3] = 255;
  3558. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3559. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3560. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3561. }
  3562. }
  3563. return imageData;
  3564. };
  3565. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3566. var image = pixel_data;
  3567. var width = header.width, height = header.height;
  3568. var color, i = 0, x, y;
  3569. var imageData = new Uint8Array(width * height * 4);
  3570. for (y = y_start; y !== y_end; y += y_step) {
  3571. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3572. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3573. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3574. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3575. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3576. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3577. }
  3578. }
  3579. return imageData;
  3580. };
  3581. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3582. var image = pixel_data;
  3583. var width = header.width, height = header.height;
  3584. var i = 0, x, y;
  3585. var imageData = new Uint8Array(width * height * 4);
  3586. for (y = y_start; y !== y_end; y += y_step) {
  3587. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3588. imageData[(x + width * y) * 4 + 3] = 255;
  3589. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3590. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3591. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3592. }
  3593. }
  3594. return imageData;
  3595. };
  3596. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3597. var image = pixel_data;
  3598. var width = header.width, height = header.height;
  3599. var i = 0, x, y;
  3600. var imageData = new Uint8Array(width * height * 4);
  3601. for (y = y_start; y !== y_end; y += y_step) {
  3602. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3604. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3605. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3606. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3607. }
  3608. }
  3609. return imageData;
  3610. };
  3611. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3612. var image = pixel_data;
  3613. var width = header.width, height = header.height;
  3614. var color, i = 0, x, y;
  3615. var imageData = new Uint8Array(width * height * 4);
  3616. for (y = y_start; y !== y_end; y += y_step) {
  3617. for (x = x_start; x !== x_end; x += x_step, i++) {
  3618. color = image[i];
  3619. imageData[(x + width * y) * 4 + 0] = color;
  3620. imageData[(x + width * y) * 4 + 1] = color;
  3621. imageData[(x + width * y) * 4 + 2] = color;
  3622. imageData[(x + width * y) * 4 + 3] = 255;
  3623. }
  3624. }
  3625. return imageData;
  3626. };
  3627. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3628. var image = pixel_data;
  3629. var width = header.width, height = header.height;
  3630. var i = 0, x, y;
  3631. var imageData = new Uint8Array(width * height * 4);
  3632. for (y = y_start; y !== y_end; y += y_step) {
  3633. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3634. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3635. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3637. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3638. }
  3639. }
  3640. return imageData;
  3641. };
  3642. TGATools._TYPE_NO_DATA = 0;
  3643. TGATools._TYPE_INDEXED = 1;
  3644. TGATools._TYPE_RGB = 2;
  3645. TGATools._TYPE_GREY = 3;
  3646. TGATools._TYPE_RLE_INDEXED = 9;
  3647. TGATools._TYPE_RLE_RGB = 10;
  3648. TGATools._TYPE_RLE_GREY = 11;
  3649. TGATools._ORIGIN_MASK = 0x30;
  3650. TGATools._ORIGIN_SHIFT = 0x04;
  3651. TGATools._ORIGIN_BL = 0x00;
  3652. TGATools._ORIGIN_BR = 0x01;
  3653. TGATools._ORIGIN_UL = 0x02;
  3654. TGATools._ORIGIN_UR = 0x03;
  3655. return TGATools;
  3656. })();
  3657. Internals.TGATools = TGATools;
  3658. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3659. })(BABYLON || (BABYLON = {}));
  3660. var BABYLON;
  3661. (function (BABYLON) {
  3662. var SmartArray = (function () {
  3663. function SmartArray(capacity) {
  3664. this.length = 0;
  3665. this._duplicateId = 0;
  3666. this.data = new Array(capacity);
  3667. this._id = SmartArray._GlobalId++;
  3668. }
  3669. SmartArray.prototype.push = function (value) {
  3670. this.data[this.length++] = value;
  3671. if (this.length > this.data.length) {
  3672. this.data.length *= 2;
  3673. }
  3674. if (!value.__smartArrayFlags) {
  3675. value.__smartArrayFlags = {};
  3676. }
  3677. value.__smartArrayFlags[this._id] = this._duplicateId;
  3678. };
  3679. SmartArray.prototype.pushNoDuplicate = function (value) {
  3680. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3681. return;
  3682. }
  3683. this.push(value);
  3684. };
  3685. SmartArray.prototype.sort = function (compareFn) {
  3686. this.data.sort(compareFn);
  3687. };
  3688. SmartArray.prototype.reset = function () {
  3689. this.length = 0;
  3690. this._duplicateId++;
  3691. };
  3692. SmartArray.prototype.concat = function (array) {
  3693. if (array.length === 0) {
  3694. return;
  3695. }
  3696. if (this.length + array.length > this.data.length) {
  3697. this.data.length = (this.length + array.length) * 2;
  3698. }
  3699. for (var index = 0; index < array.length; index++) {
  3700. this.data[this.length++] = (array.data || array)[index];
  3701. }
  3702. };
  3703. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3704. if (array.length === 0) {
  3705. return;
  3706. }
  3707. if (this.length + array.length > this.data.length) {
  3708. this.data.length = (this.length + array.length) * 2;
  3709. }
  3710. for (var index = 0; index < array.length; index++) {
  3711. var item = (array.data || array)[index];
  3712. this.pushNoDuplicate(item);
  3713. }
  3714. };
  3715. SmartArray.prototype.indexOf = function (value) {
  3716. var position = this.data.indexOf(value);
  3717. if (position >= this.length) {
  3718. return -1;
  3719. }
  3720. return position;
  3721. };
  3722. // Statics
  3723. SmartArray._GlobalId = 0;
  3724. return SmartArray;
  3725. })();
  3726. BABYLON.SmartArray = SmartArray;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var SmartCollection = (function () {
  3731. function SmartCollection(capacity) {
  3732. if (capacity === void 0) { capacity = 10; }
  3733. this.count = 0;
  3734. this._initialCapacity = capacity;
  3735. this.items = {};
  3736. this._keys = new Array(this._initialCapacity);
  3737. }
  3738. SmartCollection.prototype.add = function (key, item) {
  3739. if (this.items[key] != undefined) {
  3740. return -1;
  3741. }
  3742. this.items[key] = item;
  3743. //literal keys are always strings, but we keep source type of key in _keys array
  3744. this._keys[this.count++] = key;
  3745. if (this.count > this._keys.length) {
  3746. this._keys.length *= 2;
  3747. }
  3748. return this.count;
  3749. };
  3750. SmartCollection.prototype.remove = function (key) {
  3751. if (this.items[key] == undefined) {
  3752. return -1;
  3753. }
  3754. return this.removeItemOfIndex(this.indexOf(key));
  3755. };
  3756. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3757. if (index < this.count && index > -1) {
  3758. delete this.items[this._keys[index]];
  3759. //here, shifting by hand is better optimised than .splice
  3760. while (index < this.count) {
  3761. this._keys[index] = this._keys[index + 1];
  3762. index++;
  3763. }
  3764. }
  3765. else {
  3766. return -1;
  3767. }
  3768. return --this.count;
  3769. };
  3770. SmartCollection.prototype.indexOf = function (key) {
  3771. for (var i = 0; i !== this.count; i++) {
  3772. if (this._keys[i] === key) {
  3773. return i;
  3774. }
  3775. }
  3776. return -1;
  3777. };
  3778. SmartCollection.prototype.item = function (key) {
  3779. return this.items[key];
  3780. };
  3781. SmartCollection.prototype.getAllKeys = function () {
  3782. if (this.count > 0) {
  3783. var keys = new Array(this.count);
  3784. for (var i = 0; i < this.count; i++) {
  3785. keys[i] = this._keys[i];
  3786. }
  3787. return keys;
  3788. }
  3789. else {
  3790. return undefined;
  3791. }
  3792. };
  3793. SmartCollection.prototype.getKeyByIndex = function (index) {
  3794. if (index < this.count && index > -1) {
  3795. return this._keys[index];
  3796. }
  3797. else {
  3798. return undefined;
  3799. }
  3800. };
  3801. SmartCollection.prototype.getItemByIndex = function (index) {
  3802. if (index < this.count && index > -1) {
  3803. return this.items[this._keys[index]];
  3804. }
  3805. else {
  3806. return undefined;
  3807. }
  3808. };
  3809. SmartCollection.prototype.empty = function () {
  3810. if (this.count > 0) {
  3811. this.count = 0;
  3812. this.items = {};
  3813. this._keys = new Array(this._initialCapacity);
  3814. }
  3815. };
  3816. SmartCollection.prototype.forEach = function (block) {
  3817. var key;
  3818. for (key in this.items) {
  3819. if (this.items.hasOwnProperty(key)) {
  3820. block(this.items[key]);
  3821. }
  3822. }
  3823. };
  3824. return SmartCollection;
  3825. })();
  3826. BABYLON.SmartCollection = SmartCollection;
  3827. })(BABYLON || (BABYLON = {}));
  3828. var BABYLON;
  3829. (function (BABYLON) {
  3830. // Screenshots
  3831. var screenshotCanvas;
  3832. var cloneValue = function (source, destinationObject) {
  3833. if (!source)
  3834. return null;
  3835. if (source instanceof BABYLON.Mesh) {
  3836. return null;
  3837. }
  3838. if (source instanceof BABYLON.SubMesh) {
  3839. return source.clone(destinationObject);
  3840. }
  3841. else if (source.clone) {
  3842. return source.clone();
  3843. }
  3844. return null;
  3845. };
  3846. var Tools = (function () {
  3847. function Tools() {
  3848. }
  3849. Tools.ToHex = function (i) {
  3850. var str = i.toString(16);
  3851. if (i <= 15) {
  3852. return ("0" + str).toUpperCase();
  3853. }
  3854. return str.toUpperCase();
  3855. };
  3856. Tools.SetImmediate = function (action) {
  3857. if (window.setImmediate) {
  3858. window.setImmediate(action);
  3859. }
  3860. else {
  3861. setTimeout(action, 1);
  3862. }
  3863. };
  3864. Tools.IsExponentOfTwo = function (value) {
  3865. var count = 1;
  3866. do {
  3867. count *= 2;
  3868. } while (count < value);
  3869. return count === value;
  3870. };
  3871. Tools.GetExponentOfTwo = function (value, max) {
  3872. var count = 1;
  3873. do {
  3874. count *= 2;
  3875. } while (count < value);
  3876. if (count > max)
  3877. count = max;
  3878. return count;
  3879. };
  3880. Tools.GetFilename = function (path) {
  3881. var index = path.lastIndexOf("/");
  3882. if (index < 0)
  3883. return path;
  3884. return path.substring(index + 1);
  3885. };
  3886. Tools.GetDOMTextContent = function (element) {
  3887. var result = "";
  3888. var child = element.firstChild;
  3889. while (child) {
  3890. if (child.nodeType === 3) {
  3891. result += child.textContent;
  3892. }
  3893. child = child.nextSibling;
  3894. }
  3895. return result;
  3896. };
  3897. Tools.ToDegrees = function (angle) {
  3898. return angle * 180 / Math.PI;
  3899. };
  3900. Tools.ToRadians = function (angle) {
  3901. return angle * Math.PI / 180;
  3902. };
  3903. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3904. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3905. var output = "";
  3906. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3907. var i = 0;
  3908. var bytes = new Uint8Array(buffer);
  3909. while (i < bytes.length) {
  3910. chr1 = bytes[i++];
  3911. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3912. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3913. enc1 = chr1 >> 2;
  3914. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3915. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3916. enc4 = chr3 & 63;
  3917. if (isNaN(chr2)) {
  3918. enc3 = enc4 = 64;
  3919. }
  3920. else if (isNaN(chr3)) {
  3921. enc4 = 64;
  3922. }
  3923. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3924. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3925. }
  3926. return "data:image/png;base64," + output;
  3927. };
  3928. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3929. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3930. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3931. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3932. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3933. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3934. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3935. }
  3936. return {
  3937. minimum: minimum,
  3938. maximum: maximum
  3939. };
  3940. };
  3941. Tools.ExtractMinAndMax = function (positions, start, count) {
  3942. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3943. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3944. for (var index = start; index < start + count; index++) {
  3945. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3946. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3947. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3948. }
  3949. return {
  3950. minimum: minimum,
  3951. maximum: maximum
  3952. };
  3953. };
  3954. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3955. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3956. return undefined;
  3957. return Array.isArray(obj) ? obj : [obj];
  3958. };
  3959. // Misc.
  3960. Tools.GetPointerPrefix = function () {
  3961. var eventPrefix = "pointer";
  3962. // Check if hand.js is referenced or if the browser natively supports pointer events
  3963. if (!navigator.pointerEnabled) {
  3964. eventPrefix = "mouse";
  3965. }
  3966. return eventPrefix;
  3967. };
  3968. Tools.QueueNewFrame = function (func) {
  3969. if (window.requestAnimationFrame)
  3970. window.requestAnimationFrame(func);
  3971. else if (window.msRequestAnimationFrame)
  3972. window.msRequestAnimationFrame(func);
  3973. else if (window.webkitRequestAnimationFrame)
  3974. window.webkitRequestAnimationFrame(func);
  3975. else if (window.mozRequestAnimationFrame)
  3976. window.mozRequestAnimationFrame(func);
  3977. else if (window.oRequestAnimationFrame)
  3978. window.oRequestAnimationFrame(func);
  3979. else {
  3980. window.setTimeout(func, 16);
  3981. }
  3982. };
  3983. Tools.RequestFullscreen = function (element) {
  3984. if (element.requestFullscreen)
  3985. element.requestFullscreen();
  3986. else if (element.msRequestFullscreen)
  3987. element.msRequestFullscreen();
  3988. else if (element.webkitRequestFullscreen)
  3989. element.webkitRequestFullscreen();
  3990. else if (element.mozRequestFullScreen)
  3991. element.mozRequestFullScreen();
  3992. };
  3993. Tools.ExitFullscreen = function () {
  3994. if (document.exitFullscreen) {
  3995. document.exitFullscreen();
  3996. }
  3997. else if (document.mozCancelFullScreen) {
  3998. document.mozCancelFullScreen();
  3999. }
  4000. else if (document.webkitCancelFullScreen) {
  4001. document.webkitCancelFullScreen();
  4002. }
  4003. else if (document.msCancelFullScreen) {
  4004. document.msCancelFullScreen();
  4005. }
  4006. };
  4007. // External files
  4008. Tools.CleanUrl = function (url) {
  4009. url = url.replace(/#/mg, "%23");
  4010. return url;
  4011. };
  4012. Tools.LoadImage = function (url, onload, onerror, database) {
  4013. if (url instanceof ArrayBuffer) {
  4014. url = Tools.EncodeArrayBufferTobase64(url);
  4015. }
  4016. url = Tools.CleanUrl(url);
  4017. var img = new Image();
  4018. if (url.substr(0, 5) !== "data:") {
  4019. if (Tools.CorsBehavior) {
  4020. switch (typeof (Tools.CorsBehavior)) {
  4021. case "function":
  4022. var result = Tools.CorsBehavior(url);
  4023. if (result) {
  4024. img.crossOrigin = result;
  4025. }
  4026. break;
  4027. case "string":
  4028. default:
  4029. img.crossOrigin = Tools.CorsBehavior;
  4030. break;
  4031. }
  4032. }
  4033. }
  4034. img.onload = function () {
  4035. onload(img);
  4036. };
  4037. img.onerror = function (err) {
  4038. Tools.Error("Error while trying to load texture: " + url);
  4039. 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";
  4040. onload(img);
  4041. };
  4042. var noIndexedDB = function () {
  4043. img.src = url;
  4044. };
  4045. var loadFromIndexedDB = function () {
  4046. database.loadImageFromDB(url, img);
  4047. };
  4048. //ANY database to do!
  4049. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4050. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4051. }
  4052. else {
  4053. if (url.indexOf("file:") === -1) {
  4054. noIndexedDB();
  4055. }
  4056. else {
  4057. try {
  4058. var textureName = url.substring(5);
  4059. var blobURL;
  4060. try {
  4061. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4062. }
  4063. catch (ex) {
  4064. // Chrome doesn't support oneTimeOnly parameter
  4065. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4066. }
  4067. img.src = blobURL;
  4068. }
  4069. catch (e) {
  4070. img.src = null;
  4071. }
  4072. }
  4073. }
  4074. return img;
  4075. };
  4076. //ANY
  4077. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4078. url = Tools.CleanUrl(url);
  4079. var noIndexedDB = function () {
  4080. var request = new XMLHttpRequest();
  4081. var loadUrl = Tools.BaseUrl + url;
  4082. request.open('GET', loadUrl, true);
  4083. if (useArrayBuffer) {
  4084. request.responseType = "arraybuffer";
  4085. }
  4086. request.onprogress = progressCallBack;
  4087. request.onreadystatechange = function () {
  4088. if (request.readyState === 4) {
  4089. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4090. callback(!useArrayBuffer ? request.responseText : request.response);
  4091. }
  4092. else {
  4093. if (onError) {
  4094. onError();
  4095. }
  4096. else {
  4097. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4098. }
  4099. }
  4100. }
  4101. };
  4102. request.send(null);
  4103. };
  4104. var loadFromIndexedDB = function () {
  4105. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4106. };
  4107. if (url.indexOf("file:") !== -1) {
  4108. var fileName = url.substring(5);
  4109. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4110. }
  4111. else {
  4112. // Caching all files
  4113. if (database && database.enableSceneOffline) {
  4114. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4115. }
  4116. else {
  4117. noIndexedDB();
  4118. }
  4119. }
  4120. };
  4121. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4122. var reader = new FileReader();
  4123. reader.onload = function (e) {
  4124. //target doesn't have result from ts 1.3
  4125. callback(e.target['result']);
  4126. };
  4127. reader.onprogress = progressCallback;
  4128. reader.readAsDataURL(fileToLoad);
  4129. };
  4130. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4131. var reader = new FileReader();
  4132. reader.onerror = function (e) {
  4133. Tools.Log("Error while reading file: " + fileToLoad.name);
  4134. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4135. };
  4136. reader.onload = function (e) {
  4137. //target doesn't have result from ts 1.3
  4138. callback(e.target['result']);
  4139. };
  4140. reader.onprogress = progressCallBack;
  4141. if (!useArrayBuffer) {
  4142. // Asynchronous read
  4143. reader.readAsText(fileToLoad);
  4144. }
  4145. else {
  4146. reader.readAsArrayBuffer(fileToLoad);
  4147. }
  4148. };
  4149. //returns a downloadable url to a file content.
  4150. Tools.FileAsURL = function (content) {
  4151. var fileBlob = new Blob([content]);
  4152. var url = window.URL || window.webkitURL;
  4153. var link = url.createObjectURL(fileBlob);
  4154. return link;
  4155. };
  4156. // Misc.
  4157. Tools.Clamp = function (value, min, max) {
  4158. if (min === void 0) { min = 0; }
  4159. if (max === void 0) { max = 1; }
  4160. return Math.min(max, Math.max(min, value));
  4161. };
  4162. // Returns -1 when value is a negative number and
  4163. // +1 when value is a positive number.
  4164. Tools.Sign = function (value) {
  4165. value = +value; // convert to a number
  4166. if (value === 0 || isNaN(value))
  4167. return value;
  4168. return value > 0 ? 1 : -1;
  4169. };
  4170. Tools.Format = function (value, decimals) {
  4171. if (decimals === void 0) { decimals = 2; }
  4172. return value.toFixed(decimals);
  4173. };
  4174. Tools.CheckExtends = function (v, min, max) {
  4175. if (v.x < min.x)
  4176. min.x = v.x;
  4177. if (v.y < min.y)
  4178. min.y = v.y;
  4179. if (v.z < min.z)
  4180. min.z = v.z;
  4181. if (v.x > max.x)
  4182. max.x = v.x;
  4183. if (v.y > max.y)
  4184. max.y = v.y;
  4185. if (v.z > max.z)
  4186. max.z = v.z;
  4187. };
  4188. Tools.WithinEpsilon = function (a, b, epsilon) {
  4189. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4190. var num = a - b;
  4191. return -epsilon <= num && num <= epsilon;
  4192. };
  4193. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4194. for (var prop in source) {
  4195. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4196. continue;
  4197. }
  4198. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4199. continue;
  4200. }
  4201. var sourceValue = source[prop];
  4202. var typeOfSourceValue = typeof sourceValue;
  4203. if (typeOfSourceValue === "function") {
  4204. continue;
  4205. }
  4206. if (typeOfSourceValue === "object") {
  4207. if (sourceValue instanceof Array) {
  4208. destination[prop] = [];
  4209. if (sourceValue.length > 0) {
  4210. if (typeof sourceValue[0] == "object") {
  4211. for (var index = 0; index < sourceValue.length; index++) {
  4212. var clonedValue = cloneValue(sourceValue[index], destination);
  4213. if (destination[prop].indexOf(clonedValue) === -1) {
  4214. destination[prop].push(clonedValue);
  4215. }
  4216. }
  4217. }
  4218. else {
  4219. destination[prop] = sourceValue.slice(0);
  4220. }
  4221. }
  4222. }
  4223. else {
  4224. destination[prop] = cloneValue(sourceValue, destination);
  4225. }
  4226. }
  4227. else {
  4228. destination[prop] = sourceValue;
  4229. }
  4230. }
  4231. };
  4232. Tools.IsEmpty = function (obj) {
  4233. for (var i in obj) {
  4234. return false;
  4235. }
  4236. return true;
  4237. };
  4238. Tools.RegisterTopRootEvents = function (events) {
  4239. for (var index = 0; index < events.length; index++) {
  4240. var event = events[index];
  4241. window.addEventListener(event.name, event.handler, false);
  4242. try {
  4243. if (window.parent) {
  4244. window.parent.addEventListener(event.name, event.handler, false);
  4245. }
  4246. }
  4247. catch (e) {
  4248. }
  4249. }
  4250. };
  4251. Tools.UnregisterTopRootEvents = function (events) {
  4252. for (var index = 0; index < events.length; index++) {
  4253. var event = events[index];
  4254. window.removeEventListener(event.name, event.handler);
  4255. try {
  4256. if (window.parent) {
  4257. window.parent.removeEventListener(event.name, event.handler);
  4258. }
  4259. }
  4260. catch (e) {
  4261. }
  4262. }
  4263. };
  4264. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4265. // Read the contents of the framebuffer
  4266. var numberOfChannelsByLine = width * 4;
  4267. var halfHeight = height / 2;
  4268. //Reading datas from WebGL
  4269. var data = engine.readPixels(0, 0, width, height);
  4270. //To flip image on Y axis.
  4271. for (var i = 0; i < halfHeight; i++) {
  4272. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4273. var currentCell = j + i * numberOfChannelsByLine;
  4274. var targetLine = height - i - 1;
  4275. var targetCell = j + targetLine * numberOfChannelsByLine;
  4276. var temp = data[currentCell];
  4277. data[currentCell] = data[targetCell];
  4278. data[targetCell] = temp;
  4279. }
  4280. }
  4281. // Create a 2D canvas to store the result
  4282. if (!screenshotCanvas) {
  4283. screenshotCanvas = document.createElement('canvas');
  4284. }
  4285. screenshotCanvas.width = width;
  4286. screenshotCanvas.height = height;
  4287. var context = screenshotCanvas.getContext('2d');
  4288. // Copy the pixels to a 2D canvas
  4289. var imageData = context.createImageData(width, height);
  4290. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4291. var castData = imageData.data;
  4292. castData.set(data);
  4293. context.putImageData(imageData, 0, 0);
  4294. var base64Image = screenshotCanvas.toDataURL();
  4295. if (successCallback) {
  4296. successCallback(base64Image);
  4297. }
  4298. else {
  4299. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4300. if (("download" in document.createElement("a"))) {
  4301. var a = window.document.createElement("a");
  4302. a.href = base64Image;
  4303. var date = new Date();
  4304. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4305. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4306. window.document.body.appendChild(a);
  4307. a.addEventListener("click", function () {
  4308. a.parentElement.removeChild(a);
  4309. });
  4310. a.click();
  4311. }
  4312. else {
  4313. var newWindow = window.open("");
  4314. var img = newWindow.document.createElement("img");
  4315. img.src = base64Image;
  4316. newWindow.document.body.appendChild(img);
  4317. }
  4318. }
  4319. };
  4320. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4321. var width;
  4322. var height;
  4323. //If a precision value is specified
  4324. if (size.precision) {
  4325. width = Math.round(engine.getRenderWidth() * size.precision);
  4326. height = Math.round(width / engine.getAspectRatio(camera));
  4327. size = { width: width, height: height };
  4328. }
  4329. else if (size.width && size.height) {
  4330. width = size.width;
  4331. height = size.height;
  4332. }
  4333. else if (size.width && !size.height) {
  4334. width = size.width;
  4335. height = Math.round(width / engine.getAspectRatio(camera));
  4336. size = { width: width, height: height };
  4337. }
  4338. else if (size.height && !size.width) {
  4339. height = size.height;
  4340. width = Math.round(height * engine.getAspectRatio(camera));
  4341. size = { width: width, height: height };
  4342. }
  4343. else if (!isNaN(size)) {
  4344. height = size;
  4345. width = size;
  4346. }
  4347. else {
  4348. Tools.Error("Invalid 'size' parameter !");
  4349. return;
  4350. }
  4351. var scene = camera.getScene();
  4352. var previousCamera = null;
  4353. if (scene.activeCamera !== camera) {
  4354. previousCamera = scene.activeCamera;
  4355. scene.activeCamera = camera;
  4356. }
  4357. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4359. texture.renderList = scene.meshes;
  4360. texture.onAfterRender = function () {
  4361. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4362. };
  4363. scene.incrementRenderId();
  4364. texture.render(true);
  4365. texture.dispose();
  4366. if (previousCamera) {
  4367. scene.activeCamera = previousCamera;
  4368. }
  4369. };
  4370. // XHR response validator for local file scenario
  4371. Tools.ValidateXHRData = function (xhr, dataType) {
  4372. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4373. if (dataType === void 0) { dataType = 7; }
  4374. try {
  4375. if (dataType & 1) {
  4376. if (xhr.responseText && xhr.responseText.length > 0) {
  4377. return true;
  4378. }
  4379. else if (dataType === 1) {
  4380. return false;
  4381. }
  4382. }
  4383. if (dataType & 2) {
  4384. // Check header width and height since there is no "TGA" magic number
  4385. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4386. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4387. return true;
  4388. }
  4389. else if (dataType === 2) {
  4390. return false;
  4391. }
  4392. }
  4393. if (dataType & 4) {
  4394. // Check for the "DDS" magic number
  4395. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4396. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4397. return true;
  4398. }
  4399. else {
  4400. return false;
  4401. }
  4402. }
  4403. }
  4404. catch (e) {
  4405. }
  4406. return false;
  4407. };
  4408. Object.defineProperty(Tools, "NoneLogLevel", {
  4409. get: function () {
  4410. return Tools._NoneLogLevel;
  4411. },
  4412. enumerable: true,
  4413. configurable: true
  4414. });
  4415. Object.defineProperty(Tools, "MessageLogLevel", {
  4416. get: function () {
  4417. return Tools._MessageLogLevel;
  4418. },
  4419. enumerable: true,
  4420. configurable: true
  4421. });
  4422. Object.defineProperty(Tools, "WarningLogLevel", {
  4423. get: function () {
  4424. return Tools._WarningLogLevel;
  4425. },
  4426. enumerable: true,
  4427. configurable: true
  4428. });
  4429. Object.defineProperty(Tools, "ErrorLogLevel", {
  4430. get: function () {
  4431. return Tools._ErrorLogLevel;
  4432. },
  4433. enumerable: true,
  4434. configurable: true
  4435. });
  4436. Object.defineProperty(Tools, "AllLogLevel", {
  4437. get: function () {
  4438. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4439. },
  4440. enumerable: true,
  4441. configurable: true
  4442. });
  4443. Tools._AddLogEntry = function (entry) {
  4444. Tools._LogCache = entry + Tools._LogCache;
  4445. if (Tools.OnNewCacheEntry) {
  4446. Tools.OnNewCacheEntry(entry);
  4447. }
  4448. };
  4449. Tools._FormatMessage = function (message) {
  4450. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4451. var date = new Date();
  4452. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4453. };
  4454. Tools._LogDisabled = function (message) {
  4455. // nothing to do
  4456. };
  4457. Tools._LogEnabled = function (message) {
  4458. var formattedMessage = Tools._FormatMessage(message);
  4459. console.log("BJS - " + formattedMessage);
  4460. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4461. Tools._AddLogEntry(entry);
  4462. };
  4463. Tools._WarnDisabled = function (message) {
  4464. // nothing to do
  4465. };
  4466. Tools._WarnEnabled = function (message) {
  4467. var formattedMessage = Tools._FormatMessage(message);
  4468. console.warn("BJS - " + formattedMessage);
  4469. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4470. Tools._AddLogEntry(entry);
  4471. };
  4472. Tools._ErrorDisabled = function (message) {
  4473. // nothing to do
  4474. };
  4475. Tools._ErrorEnabled = function (message) {
  4476. Tools.errorsCount++;
  4477. var formattedMessage = Tools._FormatMessage(message);
  4478. console.error("BJS - " + formattedMessage);
  4479. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4480. Tools._AddLogEntry(entry);
  4481. };
  4482. Object.defineProperty(Tools, "LogCache", {
  4483. get: function () {
  4484. return Tools._LogCache;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. Tools.ClearLogCache = function () {
  4490. Tools._LogCache = "";
  4491. Tools.errorsCount = 0;
  4492. };
  4493. Object.defineProperty(Tools, "LogLevels", {
  4494. set: function (level) {
  4495. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4496. Tools.Log = Tools._LogEnabled;
  4497. }
  4498. else {
  4499. Tools.Log = Tools._LogDisabled;
  4500. }
  4501. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4502. Tools.Warn = Tools._WarnEnabled;
  4503. }
  4504. else {
  4505. Tools.Warn = Tools._WarnDisabled;
  4506. }
  4507. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4508. Tools.Error = Tools._ErrorEnabled;
  4509. }
  4510. else {
  4511. Tools.Error = Tools._ErrorDisabled;
  4512. }
  4513. },
  4514. enumerable: true,
  4515. configurable: true
  4516. });
  4517. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4518. get: function () {
  4519. return Tools._PerformanceNoneLogLevel;
  4520. },
  4521. enumerable: true,
  4522. configurable: true
  4523. });
  4524. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4525. get: function () {
  4526. return Tools._PerformanceUserMarkLogLevel;
  4527. },
  4528. enumerable: true,
  4529. configurable: true
  4530. });
  4531. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4532. get: function () {
  4533. return Tools._PerformanceConsoleLogLevel;
  4534. },
  4535. enumerable: true,
  4536. configurable: true
  4537. });
  4538. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4539. set: function (level) {
  4540. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4541. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4542. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4543. return;
  4544. }
  4545. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4546. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4547. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4548. return;
  4549. }
  4550. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4551. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4552. },
  4553. enumerable: true,
  4554. configurable: true
  4555. });
  4556. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4557. };
  4558. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4559. };
  4560. Tools._StartUserMark = function (counterName, condition) {
  4561. if (condition === void 0) { condition = true; }
  4562. if (!condition || !Tools._performance.mark) {
  4563. return;
  4564. }
  4565. Tools._performance.mark(counterName + "-Begin");
  4566. };
  4567. Tools._EndUserMark = function (counterName, condition) {
  4568. if (condition === void 0) { condition = true; }
  4569. if (!condition || !Tools._performance.mark) {
  4570. return;
  4571. }
  4572. Tools._performance.mark(counterName + "-End");
  4573. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4574. };
  4575. Tools._StartPerformanceConsole = function (counterName, condition) {
  4576. if (condition === void 0) { condition = true; }
  4577. if (!condition) {
  4578. return;
  4579. }
  4580. Tools._StartUserMark(counterName, condition);
  4581. if (console.time) {
  4582. console.time(counterName);
  4583. }
  4584. };
  4585. Tools._EndPerformanceConsole = function (counterName, condition) {
  4586. if (condition === void 0) { condition = true; }
  4587. if (!condition) {
  4588. return;
  4589. }
  4590. Tools._EndUserMark(counterName, condition);
  4591. if (console.time) {
  4592. console.timeEnd(counterName);
  4593. }
  4594. };
  4595. Object.defineProperty(Tools, "Now", {
  4596. get: function () {
  4597. if (window.performance && window.performance.now) {
  4598. return window.performance.now();
  4599. }
  4600. return new Date().getTime();
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Tools.BaseUrl = "";
  4606. Tools.CorsBehavior = "anonymous";
  4607. // Logs
  4608. Tools._NoneLogLevel = 0;
  4609. Tools._MessageLogLevel = 1;
  4610. Tools._WarningLogLevel = 2;
  4611. Tools._ErrorLogLevel = 4;
  4612. Tools._LogCache = "";
  4613. Tools.errorsCount = 0;
  4614. Tools.Log = Tools._LogEnabled;
  4615. Tools.Warn = Tools._WarnEnabled;
  4616. Tools.Error = Tools._ErrorEnabled;
  4617. // Performances
  4618. Tools._PerformanceNoneLogLevel = 0;
  4619. Tools._PerformanceUserMarkLogLevel = 1;
  4620. Tools._PerformanceConsoleLogLevel = 2;
  4621. Tools._performance = window.performance;
  4622. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4623. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4624. return Tools;
  4625. })();
  4626. BABYLON.Tools = Tools;
  4627. /**
  4628. * An implementation of a loop for asynchronous functions.
  4629. */
  4630. var AsyncLoop = (function () {
  4631. /**
  4632. * Constroctor.
  4633. * @param iterations the number of iterations.
  4634. * @param _fn the function to run each iteration
  4635. * @param _successCallback the callback that will be called upon succesful execution
  4636. * @param offset starting offset.
  4637. */
  4638. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4639. if (offset === void 0) { offset = 0; }
  4640. this.iterations = iterations;
  4641. this._fn = _fn;
  4642. this._successCallback = _successCallback;
  4643. this.index = offset - 1;
  4644. this._done = false;
  4645. }
  4646. /**
  4647. * Execute the next iteration. Must be called after the last iteration was finished.
  4648. */
  4649. AsyncLoop.prototype.executeNext = function () {
  4650. if (!this._done) {
  4651. if (this.index + 1 < this.iterations) {
  4652. ++this.index;
  4653. this._fn(this);
  4654. }
  4655. else {
  4656. this.breakLoop();
  4657. }
  4658. }
  4659. };
  4660. /**
  4661. * Break the loop and run the success callback.
  4662. */
  4663. AsyncLoop.prototype.breakLoop = function () {
  4664. this._done = true;
  4665. this._successCallback();
  4666. };
  4667. /**
  4668. * Helper function
  4669. */
  4670. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4671. if (offset === void 0) { offset = 0; }
  4672. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4673. loop.executeNext();
  4674. return loop;
  4675. };
  4676. /**
  4677. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4678. * @param iterations total number of iterations
  4679. * @param syncedIterations number of synchronous iterations in each async iteration.
  4680. * @param fn the function to call each iteration.
  4681. * @param callback a success call back that will be called when iterating stops.
  4682. * @param breakFunction a break condition (optional)
  4683. * @param timeout timeout settings for the setTimeout function. default - 0.
  4684. * @constructor
  4685. */
  4686. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4687. if (timeout === void 0) { timeout = 0; }
  4688. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4689. if (breakFunction && breakFunction())
  4690. loop.breakLoop();
  4691. else {
  4692. setTimeout(function () {
  4693. for (var i = 0; i < syncedIterations; ++i) {
  4694. var iteration = (loop.index * syncedIterations) + i;
  4695. if (iteration >= iterations)
  4696. break;
  4697. fn(iteration);
  4698. if (breakFunction && breakFunction()) {
  4699. loop.breakLoop();
  4700. break;
  4701. }
  4702. }
  4703. loop.executeNext();
  4704. }, timeout);
  4705. }
  4706. }, callback);
  4707. };
  4708. return AsyncLoop;
  4709. })();
  4710. BABYLON.AsyncLoop = AsyncLoop;
  4711. })(BABYLON || (BABYLON = {}));
  4712. var BABYLON;
  4713. (function (BABYLON) {
  4714. var _DepthCullingState = (function () {
  4715. function _DepthCullingState() {
  4716. this._isDepthTestDirty = false;
  4717. this._isDepthMaskDirty = false;
  4718. this._isDepthFuncDirty = false;
  4719. this._isCullFaceDirty = false;
  4720. this._isCullDirty = false;
  4721. this._isZOffsetDirty = false;
  4722. }
  4723. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4724. get: function () {
  4725. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4726. },
  4727. enumerable: true,
  4728. configurable: true
  4729. });
  4730. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4731. get: function () {
  4732. return this._zOffset;
  4733. },
  4734. set: function (value) {
  4735. if (this._zOffset === value) {
  4736. return;
  4737. }
  4738. this._zOffset = value;
  4739. this._isZOffsetDirty = true;
  4740. },
  4741. enumerable: true,
  4742. configurable: true
  4743. });
  4744. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4745. get: function () {
  4746. return this._cullFace;
  4747. },
  4748. set: function (value) {
  4749. if (this._cullFace === value) {
  4750. return;
  4751. }
  4752. this._cullFace = value;
  4753. this._isCullFaceDirty = true;
  4754. },
  4755. enumerable: true,
  4756. configurable: true
  4757. });
  4758. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4759. get: function () {
  4760. return this._cull;
  4761. },
  4762. set: function (value) {
  4763. if (this._cull === value) {
  4764. return;
  4765. }
  4766. this._cull = value;
  4767. this._isCullDirty = true;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4773. get: function () {
  4774. return this._depthFunc;
  4775. },
  4776. set: function (value) {
  4777. if (this._depthFunc === value) {
  4778. return;
  4779. }
  4780. this._depthFunc = value;
  4781. this._isDepthFuncDirty = true;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4787. get: function () {
  4788. return this._depthMask;
  4789. },
  4790. set: function (value) {
  4791. if (this._depthMask === value) {
  4792. return;
  4793. }
  4794. this._depthMask = value;
  4795. this._isDepthMaskDirty = true;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4801. get: function () {
  4802. return this._depthTest;
  4803. },
  4804. set: function (value) {
  4805. if (this._depthTest === value) {
  4806. return;
  4807. }
  4808. this._depthTest = value;
  4809. this._isDepthTestDirty = true;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. _DepthCullingState.prototype.reset = function () {
  4815. this._depthMask = true;
  4816. this._depthTest = true;
  4817. this._depthFunc = null;
  4818. this._cull = null;
  4819. this._cullFace = null;
  4820. this._zOffset = 0;
  4821. this._isDepthTestDirty = true;
  4822. this._isDepthMaskDirty = true;
  4823. this._isDepthFuncDirty = false;
  4824. this._isCullFaceDirty = false;
  4825. this._isCullDirty = false;
  4826. this._isZOffsetDirty = false;
  4827. };
  4828. _DepthCullingState.prototype.apply = function (gl) {
  4829. if (!this.isDirty) {
  4830. return;
  4831. }
  4832. // Cull
  4833. if (this._isCullDirty) {
  4834. if (this.cull) {
  4835. gl.enable(gl.CULL_FACE);
  4836. }
  4837. else {
  4838. gl.disable(gl.CULL_FACE);
  4839. }
  4840. this._isCullDirty = false;
  4841. }
  4842. // Cull face
  4843. if (this._isCullFaceDirty) {
  4844. gl.cullFace(this.cullFace);
  4845. this._isCullFaceDirty = false;
  4846. }
  4847. // Depth mask
  4848. if (this._isDepthMaskDirty) {
  4849. gl.depthMask(this.depthMask);
  4850. this._isDepthMaskDirty = false;
  4851. }
  4852. // Depth test
  4853. if (this._isDepthTestDirty) {
  4854. if (this.depthTest) {
  4855. gl.enable(gl.DEPTH_TEST);
  4856. }
  4857. else {
  4858. gl.disable(gl.DEPTH_TEST);
  4859. }
  4860. this._isDepthTestDirty = false;
  4861. }
  4862. // Depth func
  4863. if (this._isDepthFuncDirty) {
  4864. gl.depthFunc(this.depthFunc);
  4865. this._isDepthFuncDirty = false;
  4866. }
  4867. // zOffset
  4868. if (this._isZOffsetDirty) {
  4869. if (this.zOffset) {
  4870. gl.enable(gl.POLYGON_OFFSET_FILL);
  4871. gl.polygonOffset(this.zOffset, 0);
  4872. }
  4873. else {
  4874. gl.disable(gl.POLYGON_OFFSET_FILL);
  4875. }
  4876. this._isZOffsetDirty = false;
  4877. }
  4878. };
  4879. return _DepthCullingState;
  4880. })();
  4881. BABYLON._DepthCullingState = _DepthCullingState;
  4882. var _AlphaState = (function () {
  4883. function _AlphaState() {
  4884. this._isAlphaBlendDirty = false;
  4885. this._isBlendFunctionParametersDirty = false;
  4886. this._alphaBlend = false;
  4887. this._blendFunctionParameters = new Array(4);
  4888. }
  4889. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4890. get: function () {
  4891. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4892. },
  4893. enumerable: true,
  4894. configurable: true
  4895. });
  4896. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4897. get: function () {
  4898. return this._alphaBlend;
  4899. },
  4900. set: function (value) {
  4901. if (this._alphaBlend === value) {
  4902. return;
  4903. }
  4904. this._alphaBlend = value;
  4905. this._isAlphaBlendDirty = true;
  4906. },
  4907. enumerable: true,
  4908. configurable: true
  4909. });
  4910. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4911. if (this._blendFunctionParameters[0] === value0 &&
  4912. this._blendFunctionParameters[1] === value1 &&
  4913. this._blendFunctionParameters[2] === value2 &&
  4914. this._blendFunctionParameters[3] === value3) {
  4915. return;
  4916. }
  4917. this._blendFunctionParameters[0] = value0;
  4918. this._blendFunctionParameters[1] = value1;
  4919. this._blendFunctionParameters[2] = value2;
  4920. this._blendFunctionParameters[3] = value3;
  4921. this._isBlendFunctionParametersDirty = true;
  4922. };
  4923. _AlphaState.prototype.reset = function () {
  4924. this._alphaBlend = false;
  4925. this._blendFunctionParameters[0] = null;
  4926. this._blendFunctionParameters[1] = null;
  4927. this._blendFunctionParameters[2] = null;
  4928. this._blendFunctionParameters[3] = null;
  4929. this._isAlphaBlendDirty = true;
  4930. this._isBlendFunctionParametersDirty = false;
  4931. };
  4932. _AlphaState.prototype.apply = function (gl) {
  4933. if (!this.isDirty) {
  4934. return;
  4935. }
  4936. // Alpha blend
  4937. if (this._isAlphaBlendDirty) {
  4938. if (this._alphaBlend) {
  4939. gl.enable(gl.BLEND);
  4940. }
  4941. else {
  4942. gl.disable(gl.BLEND);
  4943. }
  4944. this._isAlphaBlendDirty = false;
  4945. }
  4946. // Alpha function
  4947. if (this._isBlendFunctionParametersDirty) {
  4948. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4949. this._isBlendFunctionParametersDirty = false;
  4950. }
  4951. };
  4952. return _AlphaState;
  4953. })();
  4954. BABYLON._AlphaState = _AlphaState;
  4955. var compileShader = function (gl, source, type, defines) {
  4956. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4957. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4958. gl.compileShader(shader);
  4959. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4960. throw new Error(gl.getShaderInfoLog(shader));
  4961. }
  4962. return shader;
  4963. };
  4964. var getWebGLTextureType = function (gl, type) {
  4965. var textureType = gl.UNSIGNED_BYTE;
  4966. if (type === Engine.TEXTURETYPE_FLOAT)
  4967. textureType = gl.FLOAT;
  4968. return textureType;
  4969. };
  4970. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4971. var magFilter = gl.NEAREST;
  4972. var minFilter = gl.NEAREST;
  4973. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4974. magFilter = gl.LINEAR;
  4975. if (generateMipMaps) {
  4976. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  4977. }
  4978. else {
  4979. minFilter = gl.LINEAR;
  4980. }
  4981. }
  4982. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4983. magFilter = gl.LINEAR;
  4984. if (generateMipMaps) {
  4985. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4986. }
  4987. else {
  4988. minFilter = gl.LINEAR;
  4989. }
  4990. }
  4991. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4992. magFilter = gl.NEAREST;
  4993. if (generateMipMaps) {
  4994. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  4995. }
  4996. else {
  4997. minFilter = gl.NEAREST;
  4998. }
  4999. }
  5000. return {
  5001. min: minFilter,
  5002. mag: magFilter
  5003. };
  5004. };
  5005. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5007. var engine = scene.getEngine();
  5008. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5009. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5010. gl.bindTexture(gl.TEXTURE_2D, texture);
  5011. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5012. texture._baseWidth = width;
  5013. texture._baseHeight = height;
  5014. texture._width = potWidth;
  5015. texture._height = potHeight;
  5016. texture.isReady = true;
  5017. processFunction(potWidth, potHeight);
  5018. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5021. if (!noMipmap && !isCompressed) {
  5022. gl.generateMipmap(gl.TEXTURE_2D);
  5023. }
  5024. gl.bindTexture(gl.TEXTURE_2D, null);
  5025. engine.resetTextureCache();
  5026. scene._removePendingData(texture);
  5027. };
  5028. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5029. var onload = function () {
  5030. loadedImages[index] = img;
  5031. loadedImages._internalCount++;
  5032. scene._removePendingData(img);
  5033. if (loadedImages._internalCount === 6) {
  5034. onfinish(loadedImages);
  5035. }
  5036. };
  5037. var onerror = function () {
  5038. scene._removePendingData(img);
  5039. };
  5040. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5041. scene._addPendingData(img);
  5042. };
  5043. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5044. var loadedImages = [];
  5045. loadedImages._internalCount = 0;
  5046. for (var index = 0; index < 6; index++) {
  5047. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5048. }
  5049. };
  5050. var EngineCapabilities = (function () {
  5051. function EngineCapabilities() {
  5052. }
  5053. return EngineCapabilities;
  5054. })();
  5055. BABYLON.EngineCapabilities = EngineCapabilities;
  5056. /**
  5057. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5058. */
  5059. var Engine = (function () {
  5060. /**
  5061. * @constructor
  5062. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5063. * @param {boolean} [antialias] - enable antialias
  5064. * @param options - further options to be sent to the getContext function
  5065. */
  5066. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5067. var _this = this;
  5068. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5069. // Public members
  5070. this.isFullscreen = false;
  5071. this.isPointerLock = false;
  5072. this.cullBackFaces = true;
  5073. this.renderEvenInBackground = true;
  5074. // To enable/disable IDB support and avoid XHR on .manifest
  5075. this.enableOfflineSupport = true;
  5076. this.scenes = new Array();
  5077. this._windowIsBackground = false;
  5078. this._drawCalls = 0;
  5079. this._renderingQueueLaunched = false;
  5080. this._activeRenderLoops = [];
  5081. // FPS
  5082. this.fpsRange = 60;
  5083. this.previousFramesDuration = [];
  5084. this.fps = 60;
  5085. this.deltaTime = 0;
  5086. // States
  5087. this._depthCullingState = new _DepthCullingState();
  5088. this._alphaState = new _AlphaState();
  5089. this._alphaMode = Engine.ALPHA_DISABLE;
  5090. // Cache
  5091. this._loadedTexturesCache = new Array();
  5092. this._maxTextureChannels = 16;
  5093. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5094. this._compiledEffects = {};
  5095. this._uintIndicesCurrentlySet = false;
  5096. this._renderingCanvas = canvas;
  5097. options = options || {};
  5098. options.antialias = antialias;
  5099. if (options.preserveDrawingBuffer === undefined) {
  5100. options.preserveDrawingBuffer = false;
  5101. }
  5102. // GL
  5103. try {
  5104. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5105. }
  5106. catch (e) {
  5107. throw new Error("WebGL not supported");
  5108. }
  5109. if (!this._gl) {
  5110. throw new Error("WebGL not supported");
  5111. }
  5112. this._onBlur = function () {
  5113. _this._windowIsBackground = true;
  5114. };
  5115. this._onFocus = function () {
  5116. _this._windowIsBackground = false;
  5117. };
  5118. window.addEventListener("blur", this._onBlur);
  5119. window.addEventListener("focus", this._onFocus);
  5120. // Viewport
  5121. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5122. this.resize();
  5123. // Caps
  5124. this._caps = new EngineCapabilities();
  5125. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5126. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5127. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5128. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5129. // Infos
  5130. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5131. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5132. if (rendererInfo != null) {
  5133. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5134. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5135. }
  5136. if (!this._glVendor) {
  5137. this._glVendor = "Unknown vendor";
  5138. }
  5139. if (!this._glRenderer) {
  5140. this._glRenderer = "Unknown renderer";
  5141. }
  5142. // Extensions
  5143. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5144. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5145. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5146. 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');
  5147. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5148. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5149. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5150. this._caps.highPrecisionShaderSupported = true;
  5151. if (this._gl.getShaderPrecisionFormat) {
  5152. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5153. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5154. }
  5155. // Depth buffer
  5156. this.setDepthBuffer(true);
  5157. this.setDepthFunctionToLessOrEqual();
  5158. this.setDepthWrite(true);
  5159. // Fullscreen
  5160. this._onFullscreenChange = function () {
  5161. if (document.fullscreen !== undefined) {
  5162. _this.isFullscreen = document.fullscreen;
  5163. }
  5164. else if (document.mozFullScreen !== undefined) {
  5165. _this.isFullscreen = document.mozFullScreen;
  5166. }
  5167. else if (document.webkitIsFullScreen !== undefined) {
  5168. _this.isFullscreen = document.webkitIsFullScreen;
  5169. }
  5170. else if (document.msIsFullScreen !== undefined) {
  5171. _this.isFullscreen = document.msIsFullScreen;
  5172. }
  5173. // Pointer lock
  5174. if (_this.isFullscreen && _this._pointerLockRequested) {
  5175. canvas.requestPointerLock = canvas.requestPointerLock ||
  5176. canvas.msRequestPointerLock ||
  5177. canvas.mozRequestPointerLock ||
  5178. canvas.webkitRequestPointerLock;
  5179. if (canvas.requestPointerLock) {
  5180. canvas.requestPointerLock();
  5181. }
  5182. }
  5183. };
  5184. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5185. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5186. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5187. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5188. // Pointer lock
  5189. this._onPointerLockChange = function () {
  5190. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5191. document.webkitPointerLockElement === canvas ||
  5192. document.msPointerLockElement === canvas ||
  5193. document.pointerLockElement === canvas);
  5194. };
  5195. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5196. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5197. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5198. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5199. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5200. Engine.audioEngine = new BABYLON.AudioEngine();
  5201. }
  5202. //default loading screen
  5203. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5204. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5205. }
  5206. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5207. get: function () {
  5208. return Engine._ALPHA_DISABLE;
  5209. },
  5210. enumerable: true,
  5211. configurable: true
  5212. });
  5213. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5214. get: function () {
  5215. return Engine._ALPHA_ONEONE;
  5216. },
  5217. enumerable: true,
  5218. configurable: true
  5219. });
  5220. Object.defineProperty(Engine, "ALPHA_ADD", {
  5221. get: function () {
  5222. return Engine._ALPHA_ADD;
  5223. },
  5224. enumerable: true,
  5225. configurable: true
  5226. });
  5227. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5228. get: function () {
  5229. return Engine._ALPHA_COMBINE;
  5230. },
  5231. enumerable: true,
  5232. configurable: true
  5233. });
  5234. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5235. get: function () {
  5236. return Engine._ALPHA_SUBTRACT;
  5237. },
  5238. enumerable: true,
  5239. configurable: true
  5240. });
  5241. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5242. get: function () {
  5243. return Engine._ALPHA_MULTIPLY;
  5244. },
  5245. enumerable: true,
  5246. configurable: true
  5247. });
  5248. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5249. get: function () {
  5250. return Engine._ALPHA_MAXIMIZED;
  5251. },
  5252. enumerable: true,
  5253. configurable: true
  5254. });
  5255. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5256. get: function () {
  5257. return Engine._DELAYLOADSTATE_NONE;
  5258. },
  5259. enumerable: true,
  5260. configurable: true
  5261. });
  5262. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5263. get: function () {
  5264. return Engine._DELAYLOADSTATE_LOADED;
  5265. },
  5266. enumerable: true,
  5267. configurable: true
  5268. });
  5269. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5270. get: function () {
  5271. return Engine._DELAYLOADSTATE_LOADING;
  5272. },
  5273. enumerable: true,
  5274. configurable: true
  5275. });
  5276. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5277. get: function () {
  5278. return Engine._DELAYLOADSTATE_NOTLOADED;
  5279. },
  5280. enumerable: true,
  5281. configurable: true
  5282. });
  5283. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5284. get: function () {
  5285. return Engine._TEXTUREFORMAT_ALPHA;
  5286. },
  5287. enumerable: true,
  5288. configurable: true
  5289. });
  5290. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5291. get: function () {
  5292. return Engine._TEXTUREFORMAT_LUMINANCE;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5298. get: function () {
  5299. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5300. },
  5301. enumerable: true,
  5302. configurable: true
  5303. });
  5304. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5305. get: function () {
  5306. return Engine._TEXTUREFORMAT_RGB;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5312. get: function () {
  5313. return Engine._TEXTUREFORMAT_RGBA;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5319. get: function () {
  5320. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5321. },
  5322. enumerable: true,
  5323. configurable: true
  5324. });
  5325. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5326. get: function () {
  5327. return Engine._TEXTURETYPE_FLOAT;
  5328. },
  5329. enumerable: true,
  5330. configurable: true
  5331. });
  5332. Object.defineProperty(Engine, "Version", {
  5333. get: function () {
  5334. return "2.3.0-alpha";
  5335. },
  5336. enumerable: true,
  5337. configurable: true
  5338. });
  5339. Engine.prototype._prepareWorkingCanvas = function () {
  5340. if (this._workingCanvas) {
  5341. return;
  5342. }
  5343. this._workingCanvas = document.createElement("canvas");
  5344. this._workingContext = this._workingCanvas.getContext("2d");
  5345. };
  5346. Engine.prototype.resetTextureCache = function () {
  5347. for (var index = 0; index < this._maxTextureChannels; index++) {
  5348. this._activeTexturesCache[index] = null;
  5349. }
  5350. };
  5351. Engine.prototype.getGlInfo = function () {
  5352. return {
  5353. vendor: this._glVendor,
  5354. renderer: this._glRenderer,
  5355. version: this._glVersion
  5356. };
  5357. };
  5358. Engine.prototype.getAspectRatio = function (camera) {
  5359. var viewport = camera.viewport;
  5360. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5361. };
  5362. Engine.prototype.getRenderWidth = function () {
  5363. if (this._currentRenderTarget) {
  5364. return this._currentRenderTarget._width;
  5365. }
  5366. return this._renderingCanvas.width;
  5367. };
  5368. Engine.prototype.getRenderHeight = function () {
  5369. if (this._currentRenderTarget) {
  5370. return this._currentRenderTarget._height;
  5371. }
  5372. return this._renderingCanvas.height;
  5373. };
  5374. Engine.prototype.getRenderingCanvas = function () {
  5375. return this._renderingCanvas;
  5376. };
  5377. Engine.prototype.getRenderingCanvasClientRect = function () {
  5378. return this._renderingCanvas.getBoundingClientRect();
  5379. };
  5380. Engine.prototype.setHardwareScalingLevel = function (level) {
  5381. this._hardwareScalingLevel = level;
  5382. this.resize();
  5383. };
  5384. Engine.prototype.getHardwareScalingLevel = function () {
  5385. return this._hardwareScalingLevel;
  5386. };
  5387. Engine.prototype.getLoadedTexturesCache = function () {
  5388. return this._loadedTexturesCache;
  5389. };
  5390. Engine.prototype.getCaps = function () {
  5391. return this._caps;
  5392. };
  5393. Object.defineProperty(Engine.prototype, "drawCalls", {
  5394. get: function () {
  5395. return this._drawCalls;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. // Methods
  5401. Engine.prototype.resetDrawCalls = function () {
  5402. this._drawCalls = 0;
  5403. };
  5404. Engine.prototype.setDepthFunctionToGreater = function () {
  5405. this._depthCullingState.depthFunc = this._gl.GREATER;
  5406. };
  5407. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5408. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5409. };
  5410. Engine.prototype.setDepthFunctionToLess = function () {
  5411. this._depthCullingState.depthFunc = this._gl.LESS;
  5412. };
  5413. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5414. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5415. };
  5416. /**
  5417. * stop executing a render loop function and remove it from the execution array
  5418. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5419. */
  5420. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5421. if (!renderFunction) {
  5422. this._activeRenderLoops = [];
  5423. return;
  5424. }
  5425. var index = this._activeRenderLoops.indexOf(renderFunction);
  5426. if (index >= 0) {
  5427. this._activeRenderLoops.splice(index, 1);
  5428. }
  5429. };
  5430. Engine.prototype._renderLoop = function () {
  5431. var shouldRender = true;
  5432. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5433. shouldRender = false;
  5434. }
  5435. if (shouldRender) {
  5436. // Start new frame
  5437. this.beginFrame();
  5438. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5439. var renderFunction = this._activeRenderLoops[index];
  5440. renderFunction();
  5441. }
  5442. // Present
  5443. this.endFrame();
  5444. }
  5445. if (this._activeRenderLoops.length > 0) {
  5446. // Register new frame
  5447. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5448. }
  5449. else {
  5450. this._renderingQueueLaunched = false;
  5451. }
  5452. };
  5453. /**
  5454. * Register and execute a render loop. The engine can have more than one render function.
  5455. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5456. * @example
  5457. * engine.runRenderLoop(function () {
  5458. * scene.render()
  5459. * })
  5460. */
  5461. Engine.prototype.runRenderLoop = function (renderFunction) {
  5462. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5463. return;
  5464. }
  5465. this._activeRenderLoops.push(renderFunction);
  5466. if (!this._renderingQueueLaunched) {
  5467. this._renderingQueueLaunched = true;
  5468. this._bindedRenderFunction = this._renderLoop.bind(this);
  5469. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5470. }
  5471. };
  5472. /**
  5473. * Toggle full screen mode.
  5474. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5475. */
  5476. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5477. if (this.isFullscreen) {
  5478. BABYLON.Tools.ExitFullscreen();
  5479. }
  5480. else {
  5481. this._pointerLockRequested = requestPointerLock;
  5482. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5483. }
  5484. };
  5485. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5486. this.applyStates();
  5487. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5488. if (this._depthCullingState.depthMask) {
  5489. this._gl.clearDepth(1.0);
  5490. }
  5491. var mode = 0;
  5492. if (backBuffer)
  5493. mode |= this._gl.COLOR_BUFFER_BIT;
  5494. if (depthStencil && this._depthCullingState.depthMask)
  5495. mode |= this._gl.DEPTH_BUFFER_BIT;
  5496. this._gl.clear(mode);
  5497. };
  5498. /**
  5499. * Set the WebGL's viewport
  5500. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5501. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5502. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5503. */
  5504. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5505. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5506. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5507. var x = viewport.x || 0;
  5508. var y = viewport.y || 0;
  5509. this._cachedViewport = viewport;
  5510. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5511. };
  5512. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5513. this._cachedViewport = null;
  5514. this._gl.viewport(x, y, width, height);
  5515. };
  5516. Engine.prototype.beginFrame = function () {
  5517. this._measureFps();
  5518. };
  5519. Engine.prototype.endFrame = function () {
  5520. //this.flushFramebuffer();
  5521. };
  5522. /**
  5523. * resize the view according to the canvas' size.
  5524. * @example
  5525. * window.addEventListener("resize", function () {
  5526. * engine.resize();
  5527. * });
  5528. */
  5529. Engine.prototype.resize = function () {
  5530. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5531. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5532. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5533. for (var index = 0; index < this.scenes.length; index++) {
  5534. var scene = this.scenes[index];
  5535. if (scene.debugLayer.isVisible()) {
  5536. scene.debugLayer._syncPositions();
  5537. }
  5538. }
  5539. };
  5540. /**
  5541. * force a specific size of the canvas
  5542. * @param {number} width - the new canvas' width
  5543. * @param {number} height - the new canvas' height
  5544. */
  5545. Engine.prototype.setSize = function (width, height) {
  5546. this._renderingCanvas.width = width;
  5547. this._renderingCanvas.height = height;
  5548. for (var index = 0; index < this.scenes.length; index++) {
  5549. var scene = this.scenes[index];
  5550. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5551. var cam = scene.cameras[camIndex];
  5552. cam._currentRenderId = 0;
  5553. }
  5554. }
  5555. };
  5556. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5557. this._currentRenderTarget = texture;
  5558. var gl = this._gl;
  5559. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5560. if (texture.isCube) {
  5561. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5562. }
  5563. else {
  5564. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5565. }
  5566. this._gl.viewport(0, 0, texture._width, texture._height);
  5567. this.wipeCaches();
  5568. };
  5569. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5570. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5571. this._currentRenderTarget = null;
  5572. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5573. var gl = this._gl;
  5574. gl.bindTexture(gl.TEXTURE_2D, texture);
  5575. gl.generateMipmap(gl.TEXTURE_2D);
  5576. gl.bindTexture(gl.TEXTURE_2D, null);
  5577. }
  5578. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5579. };
  5580. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5581. if (texture.generateMipMaps) {
  5582. var gl = this._gl;
  5583. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5584. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5585. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5586. }
  5587. };
  5588. Engine.prototype.flushFramebuffer = function () {
  5589. this._gl.flush();
  5590. };
  5591. Engine.prototype.restoreDefaultFramebuffer = function () {
  5592. this._currentRenderTarget = null;
  5593. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5594. this.setViewport(this._cachedViewport);
  5595. this.wipeCaches();
  5596. };
  5597. // VBOs
  5598. Engine.prototype._resetVertexBufferBinding = function () {
  5599. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5600. this._cachedVertexBuffers = null;
  5601. };
  5602. Engine.prototype.createVertexBuffer = function (vertices) {
  5603. var vbo = this._gl.createBuffer();
  5604. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5605. if (vertices instanceof Float32Array) {
  5606. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5607. }
  5608. else {
  5609. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5610. }
  5611. this._resetVertexBufferBinding();
  5612. vbo.references = 1;
  5613. return vbo;
  5614. };
  5615. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5616. var vbo = this._gl.createBuffer();
  5617. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5619. this._resetVertexBufferBinding();
  5620. vbo.references = 1;
  5621. return vbo;
  5622. };
  5623. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5624. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5625. if (offset === undefined) {
  5626. offset = 0;
  5627. }
  5628. if (vertices instanceof Float32Array) {
  5629. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5630. }
  5631. else {
  5632. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5633. }
  5634. this._resetVertexBufferBinding();
  5635. };
  5636. Engine.prototype._resetIndexBufferBinding = function () {
  5637. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5638. this._cachedIndexBuffer = null;
  5639. };
  5640. Engine.prototype.createIndexBuffer = function (indices) {
  5641. var vbo = this._gl.createBuffer();
  5642. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5643. // Check for 32 bits indices
  5644. var arrayBuffer;
  5645. var need32Bits = false;
  5646. if (this._caps.uintIndices) {
  5647. for (var index = 0; index < indices.length; index++) {
  5648. if (indices[index] > 65535) {
  5649. need32Bits = true;
  5650. break;
  5651. }
  5652. }
  5653. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5654. }
  5655. else {
  5656. arrayBuffer = new Uint16Array(indices);
  5657. }
  5658. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5659. this._resetIndexBufferBinding();
  5660. vbo.references = 1;
  5661. vbo.is32Bits = need32Bits;
  5662. return vbo;
  5663. };
  5664. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5665. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5666. this._cachedVertexBuffers = vertexBuffer;
  5667. this._cachedEffectForVertexBuffers = effect;
  5668. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5669. var offset = 0;
  5670. for (var index = 0; index < vertexDeclaration.length; index++) {
  5671. var order = effect.getAttributeLocation(index);
  5672. if (order >= 0) {
  5673. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5674. }
  5675. offset += vertexDeclaration[index] * 4;
  5676. }
  5677. }
  5678. if (this._cachedIndexBuffer !== indexBuffer) {
  5679. this._cachedIndexBuffer = indexBuffer;
  5680. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5681. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5682. }
  5683. };
  5684. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5685. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5686. this._cachedVertexBuffers = vertexBuffers;
  5687. this._cachedEffectForVertexBuffers = effect;
  5688. var attributes = effect.getAttributesNames();
  5689. for (var index = 0; index < attributes.length; index++) {
  5690. var order = effect.getAttributeLocation(index);
  5691. if (order >= 0) {
  5692. var vertexBuffer = vertexBuffers[attributes[index]];
  5693. if (!vertexBuffer) {
  5694. continue;
  5695. }
  5696. var stride = vertexBuffer.getStrideSize();
  5697. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5698. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5699. }
  5700. }
  5701. }
  5702. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5703. this._cachedIndexBuffer = indexBuffer;
  5704. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5705. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5706. }
  5707. };
  5708. Engine.prototype._releaseBuffer = function (buffer) {
  5709. buffer.references--;
  5710. if (buffer.references === 0) {
  5711. this._gl.deleteBuffer(buffer);
  5712. return true;
  5713. }
  5714. return false;
  5715. };
  5716. Engine.prototype.createInstancesBuffer = function (capacity) {
  5717. var buffer = this._gl.createBuffer();
  5718. buffer.capacity = capacity;
  5719. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5720. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5721. return buffer;
  5722. };
  5723. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5724. this._gl.deleteBuffer(buffer);
  5725. };
  5726. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5728. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5729. for (var index = 0; index < 4; index++) {
  5730. var offsetLocation = offsetLocations[index];
  5731. this._gl.enableVertexAttribArray(offsetLocation);
  5732. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5733. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5734. }
  5735. };
  5736. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5737. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5738. for (var index = 0; index < 4; index++) {
  5739. var offsetLocation = offsetLocations[index];
  5740. this._gl.disableVertexAttribArray(offsetLocation);
  5741. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5742. }
  5743. };
  5744. Engine.prototype.applyStates = function () {
  5745. this._depthCullingState.apply(this._gl);
  5746. this._alphaState.apply(this._gl);
  5747. };
  5748. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5749. // Apply states
  5750. this.applyStates();
  5751. this._drawCalls++;
  5752. // Render
  5753. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5754. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5755. if (instancesCount) {
  5756. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5757. return;
  5758. }
  5759. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5760. };
  5761. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5762. // Apply states
  5763. this.applyStates();
  5764. this._drawCalls++;
  5765. if (instancesCount) {
  5766. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5767. return;
  5768. }
  5769. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5770. };
  5771. // Shaders
  5772. Engine.prototype._releaseEffect = function (effect) {
  5773. if (this._compiledEffects[effect._key]) {
  5774. delete this._compiledEffects[effect._key];
  5775. if (effect.getProgram()) {
  5776. this._gl.deleteProgram(effect.getProgram());
  5777. }
  5778. }
  5779. };
  5780. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5781. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5782. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5783. var name = vertex + "+" + fragment + "@" + defines;
  5784. if (this._compiledEffects[name]) {
  5785. return this._compiledEffects[name];
  5786. }
  5787. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5788. effect._key = name;
  5789. this._compiledEffects[name] = effect;
  5790. return effect;
  5791. };
  5792. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5793. if (uniformsNames === void 0) { uniformsNames = []; }
  5794. if (samplers === void 0) { samplers = []; }
  5795. if (defines === void 0) { defines = ""; }
  5796. return this.createEffect({
  5797. vertex: "particles",
  5798. fragmentElement: fragmentName
  5799. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5800. };
  5801. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5802. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5803. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5804. var shaderProgram = this._gl.createProgram();
  5805. this._gl.attachShader(shaderProgram, vertexShader);
  5806. this._gl.attachShader(shaderProgram, fragmentShader);
  5807. this._gl.linkProgram(shaderProgram);
  5808. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5809. if (!linked) {
  5810. var error = this._gl.getProgramInfoLog(shaderProgram);
  5811. if (error) {
  5812. throw new Error(error);
  5813. }
  5814. }
  5815. this._gl.deleteShader(vertexShader);
  5816. this._gl.deleteShader(fragmentShader);
  5817. return shaderProgram;
  5818. };
  5819. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5820. var results = [];
  5821. for (var index = 0; index < uniformsNames.length; index++) {
  5822. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5823. }
  5824. return results;
  5825. };
  5826. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5827. var results = [];
  5828. for (var index = 0; index < attributesNames.length; index++) {
  5829. try {
  5830. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5831. }
  5832. catch (e) {
  5833. results.push(-1);
  5834. }
  5835. }
  5836. return results;
  5837. };
  5838. Engine.prototype.enableEffect = function (effect) {
  5839. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5840. if (effect && effect.onBind) {
  5841. effect.onBind(effect);
  5842. }
  5843. return;
  5844. }
  5845. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5846. // Use program
  5847. this._gl.useProgram(effect.getProgram());
  5848. for (var i in this._vertexAttribArrays) {
  5849. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5850. continue;
  5851. }
  5852. this._vertexAttribArrays[i] = false;
  5853. this._gl.disableVertexAttribArray(i);
  5854. }
  5855. var attributesCount = effect.getAttributesCount();
  5856. for (var index = 0; index < attributesCount; index++) {
  5857. // Attributes
  5858. var order = effect.getAttributeLocation(index);
  5859. if (order >= 0) {
  5860. this._vertexAttribArrays[order] = true;
  5861. this._gl.enableVertexAttribArray(order);
  5862. }
  5863. }
  5864. this._currentEffect = effect;
  5865. if (effect.onBind) {
  5866. effect.onBind(effect);
  5867. }
  5868. };
  5869. Engine.prototype.setArray = function (uniform, array) {
  5870. if (!uniform)
  5871. return;
  5872. this._gl.uniform1fv(uniform, array);
  5873. };
  5874. Engine.prototype.setArray2 = function (uniform, array) {
  5875. if (!uniform || array.length % 2 !== 0)
  5876. return;
  5877. this._gl.uniform2fv(uniform, array);
  5878. };
  5879. Engine.prototype.setArray3 = function (uniform, array) {
  5880. if (!uniform || array.length % 3 !== 0)
  5881. return;
  5882. this._gl.uniform3fv(uniform, array);
  5883. };
  5884. Engine.prototype.setArray4 = function (uniform, array) {
  5885. if (!uniform || array.length % 4 !== 0)
  5886. return;
  5887. this._gl.uniform4fv(uniform, array);
  5888. };
  5889. Engine.prototype.setMatrices = function (uniform, matrices) {
  5890. if (!uniform)
  5891. return;
  5892. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5893. };
  5894. Engine.prototype.setMatrix = function (uniform, matrix) {
  5895. if (!uniform)
  5896. return;
  5897. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5898. };
  5899. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5900. if (!uniform)
  5901. return;
  5902. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5903. };
  5904. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5905. if (!uniform)
  5906. return;
  5907. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5908. };
  5909. Engine.prototype.setFloat = function (uniform, value) {
  5910. if (!uniform)
  5911. return;
  5912. this._gl.uniform1f(uniform, value);
  5913. };
  5914. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5915. if (!uniform)
  5916. return;
  5917. this._gl.uniform2f(uniform, x, y);
  5918. };
  5919. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5920. if (!uniform)
  5921. return;
  5922. this._gl.uniform3f(uniform, x, y, z);
  5923. };
  5924. Engine.prototype.setBool = function (uniform, bool) {
  5925. if (!uniform)
  5926. return;
  5927. this._gl.uniform1i(uniform, bool);
  5928. };
  5929. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5930. if (!uniform)
  5931. return;
  5932. this._gl.uniform4f(uniform, x, y, z, w);
  5933. };
  5934. Engine.prototype.setColor3 = function (uniform, color3) {
  5935. if (!uniform)
  5936. return;
  5937. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5938. };
  5939. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5940. if (!uniform)
  5941. return;
  5942. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5943. };
  5944. // States
  5945. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5946. if (zOffset === void 0) { zOffset = 0; }
  5947. if (reverseSide === void 0) { reverseSide = false; }
  5948. // Culling
  5949. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5950. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5951. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5952. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5953. if (culling) {
  5954. this._depthCullingState.cullFace = cullFace;
  5955. this._depthCullingState.cull = true;
  5956. }
  5957. else {
  5958. this._depthCullingState.cull = false;
  5959. }
  5960. }
  5961. // Z offset
  5962. this._depthCullingState.zOffset = zOffset;
  5963. };
  5964. Engine.prototype.setDepthBuffer = function (enable) {
  5965. this._depthCullingState.depthTest = enable;
  5966. };
  5967. Engine.prototype.getDepthWrite = function () {
  5968. return this._depthCullingState.depthMask;
  5969. };
  5970. Engine.prototype.setDepthWrite = function (enable) {
  5971. this._depthCullingState.depthMask = enable;
  5972. };
  5973. Engine.prototype.setColorWrite = function (enable) {
  5974. this._gl.colorMask(enable, enable, enable, enable);
  5975. };
  5976. Engine.prototype.setAlphaMode = function (mode) {
  5977. if (this._alphaMode === mode) {
  5978. return;
  5979. }
  5980. switch (mode) {
  5981. case Engine.ALPHA_DISABLE:
  5982. this.setDepthWrite(true);
  5983. this._alphaState.alphaBlend = false;
  5984. break;
  5985. case Engine.ALPHA_COMBINE:
  5986. this.setDepthWrite(false);
  5987. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  5988. this._alphaState.alphaBlend = true;
  5989. break;
  5990. case Engine.ALPHA_ONEONE:
  5991. this.setDepthWrite(false);
  5992. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5993. this._alphaState.alphaBlend = true;
  5994. break;
  5995. case Engine.ALPHA_ADD:
  5996. this.setDepthWrite(false);
  5997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5998. this._alphaState.alphaBlend = true;
  5999. break;
  6000. case Engine.ALPHA_SUBTRACT:
  6001. this.setDepthWrite(false);
  6002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6003. this._alphaState.alphaBlend = true;
  6004. break;
  6005. case Engine.ALPHA_MULTIPLY:
  6006. this.setDepthWrite(false);
  6007. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6008. this._alphaState.alphaBlend = true;
  6009. break;
  6010. case Engine.ALPHA_MAXIMIZED:
  6011. this.setDepthWrite(false);
  6012. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6013. this._alphaState.alphaBlend = true;
  6014. break;
  6015. }
  6016. this._alphaMode = mode;
  6017. };
  6018. Engine.prototype.getAlphaMode = function () {
  6019. return this._alphaMode;
  6020. };
  6021. Engine.prototype.setAlphaTesting = function (enable) {
  6022. this._alphaTest = enable;
  6023. };
  6024. Engine.prototype.getAlphaTesting = function () {
  6025. return this._alphaTest;
  6026. };
  6027. // Textures
  6028. Engine.prototype.wipeCaches = function () {
  6029. this.resetTextureCache();
  6030. this._currentEffect = null;
  6031. this._depthCullingState.reset();
  6032. this._alphaState.reset();
  6033. this._cachedVertexBuffers = null;
  6034. this._cachedIndexBuffer = null;
  6035. this._cachedEffectForVertexBuffers = null;
  6036. };
  6037. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6038. var gl = this._gl;
  6039. gl.bindTexture(gl.TEXTURE_2D, texture);
  6040. var magFilter = gl.NEAREST;
  6041. var minFilter = gl.NEAREST;
  6042. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6043. magFilter = gl.LINEAR;
  6044. minFilter = gl.LINEAR;
  6045. }
  6046. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6047. magFilter = gl.LINEAR;
  6048. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6049. }
  6050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6052. gl.bindTexture(gl.TEXTURE_2D, null);
  6053. texture.samplingMode = samplingMode;
  6054. };
  6055. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6056. var _this = this;
  6057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6058. if (onLoad === void 0) { onLoad = null; }
  6059. if (onError === void 0) { onError = null; }
  6060. if (buffer === void 0) { buffer = null; }
  6061. var texture = this._gl.createTexture();
  6062. var extension;
  6063. var fromData = false;
  6064. if (url.substr(0, 5) === "data:") {
  6065. fromData = true;
  6066. }
  6067. if (!fromData)
  6068. extension = url.substr(url.length - 4, 4).toLowerCase();
  6069. else {
  6070. var oldUrl = url;
  6071. fromData = oldUrl.split(':');
  6072. url = oldUrl;
  6073. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6074. }
  6075. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6076. var isTGA = (extension === ".tga");
  6077. scene._addPendingData(texture);
  6078. texture.url = url;
  6079. texture.noMipmap = noMipmap;
  6080. texture.references = 1;
  6081. texture.samplingMode = samplingMode;
  6082. this._loadedTexturesCache.push(texture);
  6083. var onerror = function () {
  6084. scene._removePendingData(texture);
  6085. if (onError) {
  6086. onError();
  6087. }
  6088. };
  6089. var callback;
  6090. if (isTGA) {
  6091. callback = function (arrayBuffer) {
  6092. var data = new Uint8Array(arrayBuffer);
  6093. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6094. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6095. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6096. if (onLoad) {
  6097. onLoad();
  6098. }
  6099. }, samplingMode);
  6100. };
  6101. if (!(fromData instanceof Array))
  6102. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6103. callback(arrayBuffer);
  6104. }, onerror, scene.database, true);
  6105. else
  6106. callback(buffer);
  6107. }
  6108. else if (isDDS) {
  6109. callback = function (data) {
  6110. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6111. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6112. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6113. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6114. if (onLoad) {
  6115. onLoad();
  6116. }
  6117. }, samplingMode);
  6118. };
  6119. if (!(fromData instanceof Array))
  6120. BABYLON.Tools.LoadFile(url, function (data) {
  6121. callback(data);
  6122. }, onerror, scene.database, true);
  6123. else
  6124. callback(buffer);
  6125. }
  6126. else {
  6127. var onload = function (img) {
  6128. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6129. var isPot = (img.width === potWidth && img.height === potHeight);
  6130. if (!isPot) {
  6131. _this._prepareWorkingCanvas();
  6132. _this._workingCanvas.width = potWidth;
  6133. _this._workingCanvas.height = potHeight;
  6134. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6135. _this._workingContext.imageSmoothingEnabled = false;
  6136. _this._workingContext.mozImageSmoothingEnabled = false;
  6137. _this._workingContext.oImageSmoothingEnabled = false;
  6138. _this._workingContext.webkitImageSmoothingEnabled = false;
  6139. _this._workingContext.msImageSmoothingEnabled = false;
  6140. }
  6141. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6142. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6143. _this._workingContext.imageSmoothingEnabled = true;
  6144. _this._workingContext.mozImageSmoothingEnabled = true;
  6145. _this._workingContext.oImageSmoothingEnabled = true;
  6146. _this._workingContext.webkitImageSmoothingEnabled = true;
  6147. _this._workingContext.msImageSmoothingEnabled = true;
  6148. }
  6149. }
  6150. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6151. if (onLoad) {
  6152. onLoad();
  6153. }
  6154. }, samplingMode);
  6155. };
  6156. if (!(fromData instanceof Array))
  6157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6158. else
  6159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6160. }
  6161. return texture;
  6162. };
  6163. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6164. if (compression === void 0) { compression = null; }
  6165. var internalFormat = this._gl.RGBA;
  6166. switch (format) {
  6167. case Engine.TEXTUREFORMAT_ALPHA:
  6168. internalFormat = this._gl.ALPHA;
  6169. break;
  6170. case Engine.TEXTUREFORMAT_LUMINANCE:
  6171. internalFormat = this._gl.LUMINANCE;
  6172. break;
  6173. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6174. internalFormat = this._gl.LUMINANCE_ALPHA;
  6175. break;
  6176. case Engine.TEXTUREFORMAT_RGB:
  6177. internalFormat = this._gl.RGB;
  6178. break;
  6179. case Engine.TEXTUREFORMAT_RGBA:
  6180. internalFormat = this._gl.RGBA;
  6181. break;
  6182. }
  6183. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6184. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6185. if (compression) {
  6186. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6187. }
  6188. else {
  6189. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6190. }
  6191. if (texture.generateMipMaps) {
  6192. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6193. }
  6194. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6195. this.resetTextureCache();
  6196. texture.isReady = true;
  6197. };
  6198. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6199. if (compression === void 0) { compression = null; }
  6200. var texture = this._gl.createTexture();
  6201. texture._baseWidth = width;
  6202. texture._baseHeight = height;
  6203. texture._width = width;
  6204. texture._height = height;
  6205. texture.references = 1;
  6206. this.updateRawTexture(texture, data, format, invertY, compression);
  6207. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6208. // Filters
  6209. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6211. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6212. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6213. texture.samplingMode = samplingMode;
  6214. this._loadedTexturesCache.push(texture);
  6215. return texture;
  6216. };
  6217. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6218. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6219. var texture = this._gl.createTexture();
  6220. texture._baseWidth = width;
  6221. texture._baseHeight = height;
  6222. if (forceExponantOfTwo) {
  6223. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6224. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6225. }
  6226. this.resetTextureCache();
  6227. texture._width = width;
  6228. texture._height = height;
  6229. texture.isReady = false;
  6230. texture.generateMipMaps = generateMipMaps;
  6231. texture.references = 1;
  6232. texture.samplingMode = samplingMode;
  6233. this.updateTextureSamplingMode(samplingMode, texture);
  6234. this._loadedTexturesCache.push(texture);
  6235. return texture;
  6236. };
  6237. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6238. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6239. if (texture.isCube) {
  6240. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6241. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6242. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6243. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6244. }
  6245. else {
  6246. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6248. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6249. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6250. }
  6251. };
  6252. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6253. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6254. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6255. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6256. if (texture.generateMipMaps) {
  6257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6258. }
  6259. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6260. this.resetTextureCache();
  6261. texture.isReady = true;
  6262. };
  6263. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6264. if (texture._isDisabled) {
  6265. return;
  6266. }
  6267. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6268. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6269. try {
  6270. // Testing video texture support
  6271. if (this._videoTextureSupported === undefined) {
  6272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6273. if (this._gl.getError() !== 0) {
  6274. this._videoTextureSupported = false;
  6275. }
  6276. else {
  6277. this._videoTextureSupported = true;
  6278. }
  6279. }
  6280. // Copy video through the current working canvas if video texture is not supported
  6281. if (!this._videoTextureSupported) {
  6282. if (!texture._workingCanvas) {
  6283. texture._workingCanvas = document.createElement("canvas");
  6284. texture._workingContext = texture._workingCanvas.getContext("2d");
  6285. texture._workingCanvas.width = texture._width;
  6286. texture._workingCanvas.height = texture._height;
  6287. }
  6288. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6289. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6290. }
  6291. else {
  6292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6293. }
  6294. if (texture.generateMipMaps) {
  6295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6296. }
  6297. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6298. this.resetTextureCache();
  6299. texture.isReady = true;
  6300. }
  6301. catch (ex) {
  6302. // Something unexpected
  6303. // Let's disable the texture
  6304. texture._isDisabled = true;
  6305. }
  6306. };
  6307. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6308. // old version had a "generateMipMaps" arg instead of options.
  6309. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6310. // in the same way, generateDepthBuffer is defaulted to true
  6311. var generateMipMaps = false;
  6312. var generateDepthBuffer = true;
  6313. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6314. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6315. if (options !== undefined) {
  6316. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6317. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6318. type = options.type === undefined ? type : options.type;
  6319. if (options.samplingMode !== undefined) {
  6320. samplingMode = options.samplingMode;
  6321. }
  6322. if (type === Engine.TEXTURETYPE_FLOAT) {
  6323. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6324. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6325. }
  6326. }
  6327. var gl = this._gl;
  6328. var texture = gl.createTexture();
  6329. gl.bindTexture(gl.TEXTURE_2D, texture);
  6330. var width = size.width || size;
  6331. var height = size.height || size;
  6332. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6333. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6334. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6335. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6336. }
  6337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6342. var depthBuffer;
  6343. // Create the depth buffer
  6344. if (generateDepthBuffer) {
  6345. depthBuffer = gl.createRenderbuffer();
  6346. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6348. }
  6349. // Create the framebuffer
  6350. var framebuffer = gl.createFramebuffer();
  6351. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6352. if (generateDepthBuffer) {
  6353. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6354. }
  6355. if (generateMipMaps) {
  6356. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6357. }
  6358. // Unbind
  6359. gl.bindTexture(gl.TEXTURE_2D, null);
  6360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6361. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6362. texture._framebuffer = framebuffer;
  6363. if (generateDepthBuffer) {
  6364. texture._depthBuffer = depthBuffer;
  6365. }
  6366. texture._width = width;
  6367. texture._height = height;
  6368. texture.isReady = true;
  6369. texture.generateMipMaps = generateMipMaps;
  6370. texture.references = 1;
  6371. texture.samplingMode = samplingMode;
  6372. this.resetTextureCache();
  6373. this._loadedTexturesCache.push(texture);
  6374. return texture;
  6375. };
  6376. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6377. var gl = this._gl;
  6378. var texture = gl.createTexture();
  6379. var generateMipMaps = true;
  6380. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6381. if (options !== undefined) {
  6382. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6383. if (options.samplingMode !== undefined) {
  6384. samplingMode = options.samplingMode;
  6385. }
  6386. }
  6387. texture.isCube = true;
  6388. texture.references = 1;
  6389. texture.generateMipMaps = generateMipMaps;
  6390. texture.references = 1;
  6391. texture.samplingMode = samplingMode;
  6392. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6393. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6394. for (var face = 0; face < 6; face++) {
  6395. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6396. }
  6397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6401. // Create the depth buffer
  6402. var depthBuffer = gl.createRenderbuffer();
  6403. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6404. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6405. // Create the framebuffer
  6406. var framebuffer = gl.createFramebuffer();
  6407. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6408. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6409. // mipmaps
  6410. if (texture.generateMipMaps) {
  6411. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6412. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6413. }
  6414. // Unbind
  6415. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6416. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6417. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6418. texture._framebuffer = framebuffer;
  6419. texture._depthBuffer = depthBuffer;
  6420. this.resetTextureCache();
  6421. texture._width = size;
  6422. texture._height = size;
  6423. texture.isReady = true;
  6424. return texture;
  6425. };
  6426. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6427. var _this = this;
  6428. var gl = this._gl;
  6429. var texture = gl.createTexture();
  6430. texture.isCube = true;
  6431. texture.url = rootUrl;
  6432. texture.references = 1;
  6433. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6435. if (isDDS) {
  6436. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6437. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6438. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6439. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6440. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6441. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6442. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6443. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6444. }
  6445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6449. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6450. _this.resetTextureCache();
  6451. texture._width = info.width;
  6452. texture._height = info.height;
  6453. texture.isReady = true;
  6454. }, null, null, true);
  6455. }
  6456. else {
  6457. cascadeLoad(rootUrl, scene, function (imgs) {
  6458. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6459. var height = width;
  6460. _this._prepareWorkingCanvas();
  6461. _this._workingCanvas.width = width;
  6462. _this._workingCanvas.height = height;
  6463. var faces = [
  6464. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6465. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6466. ];
  6467. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6469. for (var index = 0; index < faces.length; index++) {
  6470. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6471. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6472. }
  6473. if (!noMipmap) {
  6474. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6475. }
  6476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6480. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6481. _this.resetTextureCache();
  6482. texture._width = width;
  6483. texture._height = height;
  6484. texture.isReady = true;
  6485. }, extensions);
  6486. }
  6487. return texture;
  6488. };
  6489. Engine.prototype._releaseTexture = function (texture) {
  6490. var gl = this._gl;
  6491. if (texture._framebuffer) {
  6492. gl.deleteFramebuffer(texture._framebuffer);
  6493. }
  6494. if (texture._depthBuffer) {
  6495. gl.deleteRenderbuffer(texture._depthBuffer);
  6496. }
  6497. gl.deleteTexture(texture);
  6498. // Unbind channels
  6499. this.unbindAllTextures();
  6500. var index = this._loadedTexturesCache.indexOf(texture);
  6501. if (index !== -1) {
  6502. this._loadedTexturesCache.splice(index, 1);
  6503. }
  6504. };
  6505. Engine.prototype.bindSamplers = function (effect) {
  6506. this._gl.useProgram(effect.getProgram());
  6507. var samplers = effect.getSamplers();
  6508. for (var index = 0; index < samplers.length; index++) {
  6509. var uniform = effect.getUniform(samplers[index]);
  6510. this._gl.uniform1i(uniform, index);
  6511. }
  6512. this._currentEffect = null;
  6513. };
  6514. Engine.prototype._bindTexture = function (channel, texture) {
  6515. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6516. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6517. this._activeTexturesCache[channel] = null;
  6518. };
  6519. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6520. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6521. };
  6522. Engine.prototype.unbindAllTextures = function () {
  6523. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6524. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6525. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6526. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6527. this._activeTexturesCache[channel] = null;
  6528. }
  6529. };
  6530. Engine.prototype.setTexture = function (channel, texture) {
  6531. if (channel < 0) {
  6532. return;
  6533. }
  6534. // Not ready?
  6535. if (!texture || !texture.isReady()) {
  6536. if (this._activeTexturesCache[channel] != null) {
  6537. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6538. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6539. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6540. this._activeTexturesCache[channel] = null;
  6541. }
  6542. return;
  6543. }
  6544. // Video
  6545. var alreadyActivated = false;
  6546. if (texture instanceof BABYLON.VideoTexture) {
  6547. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6548. alreadyActivated = true;
  6549. texture.update();
  6550. }
  6551. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6552. texture.delayLoad();
  6553. return;
  6554. }
  6555. if (this._activeTexturesCache[channel] === texture) {
  6556. return;
  6557. }
  6558. this._activeTexturesCache[channel] = texture;
  6559. var internalTexture = texture.getInternalTexture();
  6560. if (!alreadyActivated) {
  6561. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6562. }
  6563. if (internalTexture.isCube) {
  6564. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6565. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6566. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6567. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6568. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6569. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6570. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6571. }
  6572. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6573. }
  6574. else {
  6575. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6576. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6577. internalTexture._cachedWrapU = texture.wrapU;
  6578. switch (texture.wrapU) {
  6579. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6580. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6581. break;
  6582. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6584. break;
  6585. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6587. break;
  6588. }
  6589. }
  6590. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6591. internalTexture._cachedWrapV = texture.wrapV;
  6592. switch (texture.wrapV) {
  6593. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6595. break;
  6596. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6598. break;
  6599. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6601. break;
  6602. }
  6603. }
  6604. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6605. }
  6606. };
  6607. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6608. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6609. var value = texture.anisotropicFilteringLevel;
  6610. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6611. value = 1;
  6612. }
  6613. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6614. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6615. texture._cachedAnisotropicFilteringLevel = value;
  6616. }
  6617. };
  6618. Engine.prototype.readPixels = function (x, y, width, height) {
  6619. var data = new Uint8Array(height * width * 4);
  6620. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6621. return data;
  6622. };
  6623. Engine.prototype.releaseInternalTexture = function (texture) {
  6624. if (!texture) {
  6625. return;
  6626. }
  6627. texture.references--;
  6628. // Final reference ?
  6629. if (texture.references === 0) {
  6630. var texturesCache = this.getLoadedTexturesCache();
  6631. var index = texturesCache.indexOf(texture);
  6632. if (index > -1) {
  6633. texturesCache.splice(index, 1);
  6634. }
  6635. this._releaseTexture(texture);
  6636. }
  6637. };
  6638. // Dispose
  6639. Engine.prototype.dispose = function () {
  6640. this.hideLoadingUI();
  6641. this.stopRenderLoop();
  6642. // Release scenes
  6643. while (this.scenes.length) {
  6644. this.scenes[0].dispose();
  6645. }
  6646. // Release audio engine
  6647. Engine.audioEngine.dispose();
  6648. // Release effects
  6649. for (var name in this._compiledEffects) {
  6650. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6651. }
  6652. // Unbind
  6653. for (var i in this._vertexAttribArrays) {
  6654. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6655. continue;
  6656. }
  6657. this._gl.disableVertexAttribArray(i);
  6658. }
  6659. this._gl = null;
  6660. // Events
  6661. window.removeEventListener("blur", this._onBlur);
  6662. window.removeEventListener("focus", this._onFocus);
  6663. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6664. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6665. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6666. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6667. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6668. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6669. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6670. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6671. };
  6672. // Loading screen
  6673. Engine.prototype.displayLoadingUI = function () {
  6674. this._loadingScreen.displayLoadingUI();
  6675. };
  6676. Engine.prototype.hideLoadingUI = function () {
  6677. this._loadingScreen.hideLoadingUI();
  6678. };
  6679. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6680. get: function () {
  6681. return this._loadingScreen;
  6682. },
  6683. set: function (loadingScreen) {
  6684. this._loadingScreen = loadingScreen;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6690. set: function (text) {
  6691. this._loadingScreen.loadingUIText = text;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6697. set: function (color) {
  6698. this._loadingScreen.loadingUIBackgroundColor = color;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. // FPS
  6704. Engine.prototype.getFps = function () {
  6705. return this.fps;
  6706. };
  6707. Engine.prototype.getDeltaTime = function () {
  6708. return this.deltaTime;
  6709. };
  6710. Engine.prototype._measureFps = function () {
  6711. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6712. var length = this.previousFramesDuration.length;
  6713. if (length >= 2) {
  6714. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6715. }
  6716. if (length >= this.fpsRange) {
  6717. if (length > this.fpsRange) {
  6718. this.previousFramesDuration.splice(0, 1);
  6719. length = this.previousFramesDuration.length;
  6720. }
  6721. var sum = 0;
  6722. for (var id = 0; id < length - 1; id++) {
  6723. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6724. }
  6725. this.fps = 1000.0 / (sum / (length - 1));
  6726. }
  6727. };
  6728. // Statics
  6729. Engine.isSupported = function () {
  6730. try {
  6731. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6732. if (navigator.isCocoonJS) {
  6733. return true;
  6734. }
  6735. var tempcanvas = document.createElement("canvas");
  6736. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6737. return gl != null && !!window.WebGLRenderingContext;
  6738. }
  6739. catch (e) {
  6740. return false;
  6741. }
  6742. };
  6743. // Const statics
  6744. Engine._ALPHA_DISABLE = 0;
  6745. Engine._ALPHA_ADD = 1;
  6746. Engine._ALPHA_COMBINE = 2;
  6747. Engine._ALPHA_SUBTRACT = 3;
  6748. Engine._ALPHA_MULTIPLY = 4;
  6749. Engine._ALPHA_MAXIMIZED = 5;
  6750. Engine._ALPHA_ONEONE = 6;
  6751. Engine._DELAYLOADSTATE_NONE = 0;
  6752. Engine._DELAYLOADSTATE_LOADED = 1;
  6753. Engine._DELAYLOADSTATE_LOADING = 2;
  6754. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6755. Engine._TEXTUREFORMAT_ALPHA = 0;
  6756. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6757. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6758. Engine._TEXTUREFORMAT_RGB = 4;
  6759. Engine._TEXTUREFORMAT_RGBA = 5;
  6760. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6761. Engine._TEXTURETYPE_FLOAT = 1;
  6762. // Updatable statics so stick with vars here
  6763. Engine.Epsilon = 0.001;
  6764. Engine.CollisionsEpsilon = 0.001;
  6765. Engine.CodeRepository = "src/";
  6766. Engine.ShadersRepository = "src/Shaders/";
  6767. return Engine;
  6768. })();
  6769. BABYLON.Engine = Engine;
  6770. })(BABYLON || (BABYLON = {}));
  6771. var BABYLON;
  6772. (function (BABYLON) {
  6773. /**
  6774. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6775. */
  6776. var Node = (function () {
  6777. /**
  6778. * @constructor
  6779. * @param {string} name - the name and id to be given to this node
  6780. * @param {BABYLON.Scene} the scene this node will be added to
  6781. */
  6782. function Node(name, scene) {
  6783. this.state = "";
  6784. this.animations = new Array();
  6785. this._childrenFlag = -1;
  6786. this._isEnabled = true;
  6787. this._isReady = true;
  6788. this._currentRenderId = -1;
  6789. this._parentRenderId = -1;
  6790. this.name = name;
  6791. this.id = name;
  6792. this._scene = scene;
  6793. this._initCache();
  6794. }
  6795. Node.prototype.getScene = function () {
  6796. return this._scene;
  6797. };
  6798. Node.prototype.getEngine = function () {
  6799. return this._scene.getEngine();
  6800. };
  6801. // override it in derived class
  6802. Node.prototype.getWorldMatrix = function () {
  6803. return BABYLON.Matrix.Identity();
  6804. };
  6805. // override it in derived class if you add new variables to the cache
  6806. // and call the parent class method
  6807. Node.prototype._initCache = function () {
  6808. this._cache = {};
  6809. this._cache.parent = undefined;
  6810. };
  6811. Node.prototype.updateCache = function (force) {
  6812. if (!force && this.isSynchronized())
  6813. return;
  6814. this._cache.parent = this.parent;
  6815. this._updateCache();
  6816. };
  6817. // override it in derived class if you add new variables to the cache
  6818. // and call the parent class method if !ignoreParentClass
  6819. Node.prototype._updateCache = function (ignoreParentClass) {
  6820. };
  6821. // override it in derived class if you add new variables to the cache
  6822. Node.prototype._isSynchronized = function () {
  6823. return true;
  6824. };
  6825. Node.prototype._markSyncedWithParent = function () {
  6826. this._parentRenderId = this.parent._currentRenderId;
  6827. };
  6828. Node.prototype.isSynchronizedWithParent = function () {
  6829. if (!this.parent) {
  6830. return true;
  6831. }
  6832. if (this._parentRenderId !== this.parent._currentRenderId) {
  6833. return false;
  6834. }
  6835. return this.parent.isSynchronized();
  6836. };
  6837. Node.prototype.isSynchronized = function (updateCache) {
  6838. var check = this.hasNewParent();
  6839. check = check || !this.isSynchronizedWithParent();
  6840. check = check || !this._isSynchronized();
  6841. if (updateCache)
  6842. this.updateCache(true);
  6843. return !check;
  6844. };
  6845. Node.prototype.hasNewParent = function (update) {
  6846. if (this._cache.parent === this.parent)
  6847. return false;
  6848. if (update)
  6849. this._cache.parent = this.parent;
  6850. return true;
  6851. };
  6852. /**
  6853. * Is this node ready to be used/rendered
  6854. * @return {boolean} is it ready
  6855. */
  6856. Node.prototype.isReady = function () {
  6857. return this._isReady;
  6858. };
  6859. /**
  6860. * Is this node enabled.
  6861. * If the node has a parent and is enabled, the parent will be inspected as well.
  6862. * @return {boolean} whether this node (and its parent) is enabled.
  6863. * @see setEnabled
  6864. */
  6865. Node.prototype.isEnabled = function () {
  6866. if (!this._isEnabled) {
  6867. return false;
  6868. }
  6869. if (this.parent) {
  6870. return this.parent.isEnabled();
  6871. }
  6872. return true;
  6873. };
  6874. /**
  6875. * Set the enabled state of this node.
  6876. * @param {boolean} value - the new enabled state
  6877. * @see isEnabled
  6878. */
  6879. Node.prototype.setEnabled = function (value) {
  6880. this._isEnabled = value;
  6881. };
  6882. /**
  6883. * Is this node a descendant of the given node.
  6884. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6885. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6886. * @see parent
  6887. */
  6888. Node.prototype.isDescendantOf = function (ancestor) {
  6889. if (this.parent) {
  6890. if (this.parent === ancestor) {
  6891. return true;
  6892. }
  6893. return this.parent.isDescendantOf(ancestor);
  6894. }
  6895. return false;
  6896. };
  6897. Node.prototype._getDescendants = function (list, results) {
  6898. for (var index = 0; index < list.length; index++) {
  6899. var item = list[index];
  6900. if (item.isDescendantOf(this)) {
  6901. results.push(item);
  6902. }
  6903. }
  6904. };
  6905. /**
  6906. * Will return all nodes that have this node as parent.
  6907. * @return {BABYLON.Node[]} all children nodes of all types.
  6908. */
  6909. Node.prototype.getDescendants = function () {
  6910. var results = [];
  6911. this._getDescendants(this._scene.meshes, results);
  6912. this._getDescendants(this._scene.lights, results);
  6913. this._getDescendants(this._scene.cameras, results);
  6914. return results;
  6915. };
  6916. Node.prototype._setReady = function (state) {
  6917. if (state === this._isReady) {
  6918. return;
  6919. }
  6920. if (!state) {
  6921. this._isReady = false;
  6922. return;
  6923. }
  6924. this._isReady = true;
  6925. if (this.onReady) {
  6926. this.onReady(this);
  6927. }
  6928. };
  6929. Node.prototype.getAnimationByName = function (name) {
  6930. for (var i = 0; i < this.animations.length; i++) {
  6931. var animation = this.animations[i];
  6932. if (animation.name === name) {
  6933. return animation;
  6934. }
  6935. }
  6936. return null;
  6937. };
  6938. return Node;
  6939. })();
  6940. BABYLON.Node = Node;
  6941. })(BABYLON || (BABYLON = {}));
  6942. var BABYLON;
  6943. (function (BABYLON) {
  6944. var FilesInput = (function () {
  6945. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6946. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6947. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6948. this._engine = p_engine;
  6949. this._canvas = p_canvas;
  6950. this._currentScene = p_scene;
  6951. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6952. this._progressCallback = p_progressCallback;
  6953. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6954. this._textureLoadingCallback = p_textureLoadingCallback;
  6955. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6956. }
  6957. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6958. var _this = this;
  6959. if (p_elementToMonitor) {
  6960. this._elementToMonitor = p_elementToMonitor;
  6961. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6962. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6963. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6964. }
  6965. };
  6966. FilesInput.prototype.renderFunction = function () {
  6967. if (this._additionnalRenderLoopLogicCallback) {
  6968. this._additionnalRenderLoopLogicCallback();
  6969. }
  6970. if (this._currentScene) {
  6971. if (this._textureLoadingCallback) {
  6972. var remaining = this._currentScene.getWaitingItemsCount();
  6973. if (remaining > 0) {
  6974. this._textureLoadingCallback(remaining);
  6975. }
  6976. }
  6977. this._currentScene.render();
  6978. }
  6979. };
  6980. FilesInput.prototype.drag = function (e) {
  6981. e.stopPropagation();
  6982. e.preventDefault();
  6983. };
  6984. FilesInput.prototype.drop = function (eventDrop) {
  6985. eventDrop.stopPropagation();
  6986. eventDrop.preventDefault();
  6987. this.loadFiles(eventDrop);
  6988. };
  6989. FilesInput.prototype.loadFiles = function (event) {
  6990. if (this._startingProcessingFilesCallback)
  6991. this._startingProcessingFilesCallback();
  6992. // Handling data transfer via drag'n'drop
  6993. if (event && event.dataTransfer && event.dataTransfer.files) {
  6994. this._filesToLoad = event.dataTransfer.files;
  6995. }
  6996. // Handling files from input files
  6997. if (event && event.target && event.target.files) {
  6998. this._filesToLoad = event.target.files;
  6999. }
  7000. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7001. for (var i = 0; i < this._filesToLoad.length; i++) {
  7002. switch (this._filesToLoad[i].type) {
  7003. case "image/jpeg":
  7004. case "image/png":
  7005. case "image/bmp":
  7006. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7007. break;
  7008. case "image/targa":
  7009. case "image/vnd.ms-dds":
  7010. case "audio/wav":
  7011. case "audio/x-wav":
  7012. case "audio/mp3":
  7013. case "audio/mpeg":
  7014. case "audio/mpeg3":
  7015. case "audio/x-mpeg-3":
  7016. case "audio/ogg":
  7017. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7018. break;
  7019. default:
  7020. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7021. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7022. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7023. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7024. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7025. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7026. this._sceneFileToLoad = this._filesToLoad[i];
  7027. }
  7028. break;
  7029. }
  7030. }
  7031. this.reload();
  7032. }
  7033. };
  7034. FilesInput.prototype.reload = function () {
  7035. var _this = this;
  7036. var that = this;
  7037. // If a ".babylon" file has been provided
  7038. if (this._sceneFileToLoad) {
  7039. if (this._currentScene) {
  7040. if (BABYLON.Tools.errorsCount > 0) {
  7041. BABYLON.Tools.ClearLogCache();
  7042. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7043. }
  7044. this._engine.stopRenderLoop();
  7045. this._currentScene.dispose();
  7046. }
  7047. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7048. that._currentScene = newScene;
  7049. // Wait for textures and shaders to be ready
  7050. that._currentScene.executeWhenReady(function () {
  7051. // Attach camera to canvas inputs
  7052. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7053. that._currentScene.createDefaultCameraOrLight();
  7054. }
  7055. that._currentScene.activeCamera.attachControl(that._canvas);
  7056. if (that._sceneLoadedCallback) {
  7057. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7058. }
  7059. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7060. });
  7061. }, function (progress) {
  7062. if (_this._progressCallback) {
  7063. _this._progressCallback(progress);
  7064. }
  7065. });
  7066. }
  7067. else {
  7068. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7069. }
  7070. };
  7071. FilesInput.FilesTextures = new Array();
  7072. FilesInput.FilesToLoad = new Array();
  7073. return FilesInput;
  7074. })();
  7075. BABYLON.FilesInput = FilesInput;
  7076. })(BABYLON || (BABYLON = {}));
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. var IntersectionInfo = (function () {
  7080. function IntersectionInfo(bu, bv, distance) {
  7081. this.bu = bu;
  7082. this.bv = bv;
  7083. this.distance = distance;
  7084. this.faceId = 0;
  7085. this.subMeshId = 0;
  7086. }
  7087. return IntersectionInfo;
  7088. })();
  7089. BABYLON.IntersectionInfo = IntersectionInfo;
  7090. var PickingInfo = (function () {
  7091. function PickingInfo() {
  7092. this.hit = false;
  7093. this.distance = 0;
  7094. this.pickedPoint = null;
  7095. this.pickedMesh = null;
  7096. this.bu = 0;
  7097. this.bv = 0;
  7098. this.faceId = -1;
  7099. this.subMeshId = 0;
  7100. this.pickedSprite = null;
  7101. }
  7102. // Methods
  7103. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7104. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7105. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7106. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7107. return null;
  7108. }
  7109. var indices = this.pickedMesh.getIndices();
  7110. var result;
  7111. if (useVerticesNormals) {
  7112. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7113. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7114. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7115. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7116. normal0 = normal0.scale(this.bu);
  7117. normal1 = normal1.scale(this.bv);
  7118. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7119. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7120. }
  7121. else {
  7122. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7123. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7124. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7125. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7126. var p1p2 = vertex1.subtract(vertex2);
  7127. var p3p2 = vertex3.subtract(vertex2);
  7128. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7129. }
  7130. if (useWorldCoordinates) {
  7131. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7132. }
  7133. return BABYLON.Vector3.Normalize(result);
  7134. };
  7135. PickingInfo.prototype.getTextureCoordinates = function () {
  7136. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7137. return null;
  7138. }
  7139. var indices = this.pickedMesh.getIndices();
  7140. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7141. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7142. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7143. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7144. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7145. uv1 = uv1.scale(this.bu);
  7146. uv2 = uv2.scale(this.bv);
  7147. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7148. };
  7149. return PickingInfo;
  7150. })();
  7151. BABYLON.PickingInfo = PickingInfo;
  7152. })(BABYLON || (BABYLON = {}));
  7153. var BABYLON;
  7154. (function (BABYLON) {
  7155. var BoundingSphere = (function () {
  7156. function BoundingSphere(minimum, maximum) {
  7157. this.minimum = minimum;
  7158. this.maximum = maximum;
  7159. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7160. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7161. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7162. this.radius = distance * 0.5;
  7163. this.centerWorld = BABYLON.Vector3.Zero();
  7164. this._update(BABYLON.Matrix.Identity());
  7165. }
  7166. // Methods
  7167. BoundingSphere.prototype._update = function (world) {
  7168. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7169. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7170. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7171. };
  7172. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7173. for (var i = 0; i < 6; i++) {
  7174. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7175. return false;
  7176. }
  7177. return true;
  7178. };
  7179. BoundingSphere.prototype.intersectsPoint = function (point) {
  7180. var x = this.centerWorld.x - point.x;
  7181. var y = this.centerWorld.y - point.y;
  7182. var z = this.centerWorld.z - point.z;
  7183. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7184. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7185. return false;
  7186. return true;
  7187. };
  7188. // Statics
  7189. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7190. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7191. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7192. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7193. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7194. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7195. return false;
  7196. return true;
  7197. };
  7198. return BoundingSphere;
  7199. })();
  7200. BABYLON.BoundingSphere = BoundingSphere;
  7201. })(BABYLON || (BABYLON = {}));
  7202. var BABYLON;
  7203. (function (BABYLON) {
  7204. var BoundingBox = (function () {
  7205. function BoundingBox(minimum, maximum) {
  7206. this.minimum = minimum;
  7207. this.maximum = maximum;
  7208. this.vectors = new Array();
  7209. this.vectorsWorld = new Array();
  7210. // Bounding vectors
  7211. this.vectors.push(this.minimum.clone());
  7212. this.vectors.push(this.maximum.clone());
  7213. this.vectors.push(this.minimum.clone());
  7214. this.vectors[2].x = this.maximum.x;
  7215. this.vectors.push(this.minimum.clone());
  7216. this.vectors[3].y = this.maximum.y;
  7217. this.vectors.push(this.minimum.clone());
  7218. this.vectors[4].z = this.maximum.z;
  7219. this.vectors.push(this.maximum.clone());
  7220. this.vectors[5].z = this.minimum.z;
  7221. this.vectors.push(this.maximum.clone());
  7222. this.vectors[6].x = this.minimum.x;
  7223. this.vectors.push(this.maximum.clone());
  7224. this.vectors[7].y = this.minimum.y;
  7225. // OBB
  7226. this.center = this.maximum.add(this.minimum).scale(0.5);
  7227. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7228. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7229. // World
  7230. for (var index = 0; index < this.vectors.length; index++) {
  7231. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7232. }
  7233. this.minimumWorld = BABYLON.Vector3.Zero();
  7234. this.maximumWorld = BABYLON.Vector3.Zero();
  7235. this._update(BABYLON.Matrix.Identity());
  7236. }
  7237. // Methods
  7238. BoundingBox.prototype.getWorldMatrix = function () {
  7239. return this._worldMatrix;
  7240. };
  7241. BoundingBox.prototype._update = function (world) {
  7242. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7243. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7244. for (var index = 0; index < this.vectors.length; index++) {
  7245. var v = this.vectorsWorld[index];
  7246. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7247. if (v.x < this.minimumWorld.x)
  7248. this.minimumWorld.x = v.x;
  7249. if (v.y < this.minimumWorld.y)
  7250. this.minimumWorld.y = v.y;
  7251. if (v.z < this.minimumWorld.z)
  7252. this.minimumWorld.z = v.z;
  7253. if (v.x > this.maximumWorld.x)
  7254. this.maximumWorld.x = v.x;
  7255. if (v.y > this.maximumWorld.y)
  7256. this.maximumWorld.y = v.y;
  7257. if (v.z > this.maximumWorld.z)
  7258. this.maximumWorld.z = v.z;
  7259. }
  7260. // OBB
  7261. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7262. this.center.scaleInPlace(0.5);
  7263. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7264. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7265. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7266. this._worldMatrix = world;
  7267. };
  7268. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7269. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7270. };
  7271. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7272. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7273. };
  7274. BoundingBox.prototype.intersectsPoint = function (point) {
  7275. var delta = -BABYLON.Engine.Epsilon;
  7276. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7277. return false;
  7278. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7279. return false;
  7280. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7281. return false;
  7282. return true;
  7283. };
  7284. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7285. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7286. };
  7287. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7288. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7289. return false;
  7290. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7291. return false;
  7292. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7293. return false;
  7294. return true;
  7295. };
  7296. // Statics
  7297. BoundingBox.Intersects = function (box0, box1) {
  7298. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7299. return false;
  7300. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7301. return false;
  7302. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7303. return false;
  7304. return true;
  7305. };
  7306. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7307. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7308. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7309. return (num <= (sphereRadius * sphereRadius));
  7310. };
  7311. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7312. for (var p = 0; p < 6; p++) {
  7313. for (var i = 0; i < 8; i++) {
  7314. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7315. return false;
  7316. }
  7317. }
  7318. }
  7319. return true;
  7320. };
  7321. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7322. for (var p = 0; p < 6; p++) {
  7323. var inCount = 8;
  7324. for (var i = 0; i < 8; i++) {
  7325. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7326. --inCount;
  7327. }
  7328. else {
  7329. break;
  7330. }
  7331. }
  7332. if (inCount === 0)
  7333. return false;
  7334. }
  7335. return true;
  7336. };
  7337. return BoundingBox;
  7338. })();
  7339. BABYLON.BoundingBox = BoundingBox;
  7340. })(BABYLON || (BABYLON = {}));
  7341. var BABYLON;
  7342. (function (BABYLON) {
  7343. var computeBoxExtents = function (axis, box) {
  7344. var p = BABYLON.Vector3.Dot(box.center, axis);
  7345. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7346. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7347. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7348. var r = r0 + r1 + r2;
  7349. return {
  7350. min: p - r,
  7351. max: p + r
  7352. };
  7353. };
  7354. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7355. var axisOverlap = function (axis, box0, box1) {
  7356. var result0 = computeBoxExtents(axis, box0);
  7357. var result1 = computeBoxExtents(axis, box1);
  7358. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7359. };
  7360. var BoundingInfo = (function () {
  7361. function BoundingInfo(minimum, maximum) {
  7362. this.minimum = minimum;
  7363. this.maximum = maximum;
  7364. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7365. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7366. }
  7367. // Methods
  7368. BoundingInfo.prototype._update = function (world) {
  7369. this.boundingBox._update(world);
  7370. this.boundingSphere._update(world);
  7371. };
  7372. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7373. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7374. return false;
  7375. return this.boundingBox.isInFrustum(frustumPlanes);
  7376. };
  7377. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7378. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7379. };
  7380. BoundingInfo.prototype._checkCollision = function (collider) {
  7381. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7382. };
  7383. BoundingInfo.prototype.intersectsPoint = function (point) {
  7384. if (!this.boundingSphere.centerWorld) {
  7385. return false;
  7386. }
  7387. if (!this.boundingSphere.intersectsPoint(point)) {
  7388. return false;
  7389. }
  7390. if (!this.boundingBox.intersectsPoint(point)) {
  7391. return false;
  7392. }
  7393. return true;
  7394. };
  7395. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7396. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7397. return false;
  7398. }
  7399. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7400. return false;
  7401. }
  7402. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7403. return false;
  7404. }
  7405. if (!precise) {
  7406. return true;
  7407. }
  7408. var box0 = this.boundingBox;
  7409. var box1 = boundingInfo.boundingBox;
  7410. if (!axisOverlap(box0.directions[0], box0, box1))
  7411. return false;
  7412. if (!axisOverlap(box0.directions[1], box0, box1))
  7413. return false;
  7414. if (!axisOverlap(box0.directions[2], box0, box1))
  7415. return false;
  7416. if (!axisOverlap(box1.directions[0], box0, box1))
  7417. return false;
  7418. if (!axisOverlap(box1.directions[1], box0, box1))
  7419. return false;
  7420. if (!axisOverlap(box1.directions[2], box0, box1))
  7421. return false;
  7422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7423. return false;
  7424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7425. return false;
  7426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7427. return false;
  7428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7429. return false;
  7430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7431. return false;
  7432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7433. return false;
  7434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7435. return false;
  7436. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7437. return false;
  7438. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7439. return false;
  7440. return true;
  7441. };
  7442. return BoundingInfo;
  7443. })();
  7444. BABYLON.BoundingInfo = BoundingInfo;
  7445. })(BABYLON || (BABYLON = {}));
  7446. var BABYLON;
  7447. (function (BABYLON) {
  7448. var AbstractMesh = (function (_super) {
  7449. __extends(AbstractMesh, _super);
  7450. function AbstractMesh(name, scene) {
  7451. var _this = this;
  7452. _super.call(this, name, scene);
  7453. // Properties
  7454. this.definedFacingForward = true; // orientation for POV movement & rotation
  7455. this.position = new BABYLON.Vector3(0, 0, 0);
  7456. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7457. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7458. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7459. this.visibility = 1.0;
  7460. this.alphaIndex = Number.MAX_VALUE;
  7461. this.infiniteDistance = false;
  7462. this.isVisible = true;
  7463. this.isPickable = true;
  7464. this.showBoundingBox = false;
  7465. this.showSubMeshesBoundingBox = false;
  7466. this.onDispose = null;
  7467. this.isBlocker = false;
  7468. this.renderingGroupId = 0;
  7469. this.receiveShadows = false;
  7470. this.renderOutline = false;
  7471. this.outlineColor = BABYLON.Color3.Red();
  7472. this.outlineWidth = 0.02;
  7473. this.renderOverlay = false;
  7474. this.overlayColor = BABYLON.Color3.Red();
  7475. this.overlayAlpha = 0.5;
  7476. this.hasVertexAlpha = false;
  7477. this.useVertexColors = true;
  7478. this.applyFog = true;
  7479. this.computeBonesUsingShaders = true;
  7480. this.scalingDeterminant = 1;
  7481. this.numBoneInfluencers = 4;
  7482. this.useOctreeForRenderingSelection = true;
  7483. this.useOctreeForPicking = true;
  7484. this.useOctreeForCollisions = true;
  7485. this.layerMask = 0x0FFFFFFF;
  7486. this.alwaysSelectAsActiveMesh = false;
  7487. // Physics
  7488. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7489. // Collisions
  7490. this._checkCollisions = false;
  7491. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7492. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7493. this._collider = new BABYLON.Collider();
  7494. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7495. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7496. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7497. // Edges
  7498. this.edgesWidth = 1;
  7499. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7500. // Cache
  7501. this._localScaling = BABYLON.Matrix.Zero();
  7502. this._localRotation = BABYLON.Matrix.Zero();
  7503. this._localTranslation = BABYLON.Matrix.Zero();
  7504. this._localBillboard = BABYLON.Matrix.Zero();
  7505. this._localPivotScaling = BABYLON.Matrix.Zero();
  7506. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7507. this._localWorld = BABYLON.Matrix.Zero();
  7508. this._worldMatrix = BABYLON.Matrix.Zero();
  7509. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7510. this._absolutePosition = BABYLON.Vector3.Zero();
  7511. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7512. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7513. this._isDirty = false;
  7514. this._pivotMatrix = BABYLON.Matrix.Identity();
  7515. this._isDisposed = false;
  7516. this._renderId = 0;
  7517. this._intersectionsInProgress = new Array();
  7518. this._onAfterWorldMatrixUpdate = new Array();
  7519. this._isWorldMatrixFrozen = false;
  7520. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7521. if (collidedMesh === void 0) { collidedMesh = null; }
  7522. //TODO move this to the collision coordinator!
  7523. if (_this.getScene().workerCollisions)
  7524. newPosition.multiplyInPlace(_this._collider.radius);
  7525. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7526. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7527. _this.position.addInPlace(_this._diffPositionForCollisions);
  7528. }
  7529. if (_this.onCollide && collidedMesh) {
  7530. _this.onCollide(collidedMesh);
  7531. }
  7532. if (_this.onCollisionPositionChange) {
  7533. _this.onCollisionPositionChange(_this.position);
  7534. }
  7535. };
  7536. scene.addMesh(this);
  7537. }
  7538. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7539. get: function () {
  7540. return AbstractMesh._BILLBOARDMODE_NONE;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7546. get: function () {
  7547. return AbstractMesh._BILLBOARDMODE_X;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7553. get: function () {
  7554. return AbstractMesh._BILLBOARDMODE_Y;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7560. get: function () {
  7561. return AbstractMesh._BILLBOARDMODE_Z;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7567. get: function () {
  7568. return AbstractMesh._BILLBOARDMODE_ALL;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. // Methods
  7574. AbstractMesh.prototype.disableEdgesRendering = function () {
  7575. if (this._edgesRenderer !== undefined) {
  7576. this._edgesRenderer.dispose();
  7577. this._edgesRenderer = undefined;
  7578. }
  7579. };
  7580. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7581. if (epsilon === void 0) { epsilon = 0.95; }
  7582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7583. this.disableEdgesRendering();
  7584. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7585. };
  7586. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7587. get: function () {
  7588. return false;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. AbstractMesh.prototype.getLOD = function (camera) {
  7594. return this;
  7595. };
  7596. AbstractMesh.prototype.getTotalVertices = function () {
  7597. return 0;
  7598. };
  7599. AbstractMesh.prototype.getIndices = function () {
  7600. return null;
  7601. };
  7602. AbstractMesh.prototype.getVerticesData = function (kind) {
  7603. return null;
  7604. };
  7605. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7606. return false;
  7607. };
  7608. AbstractMesh.prototype.getBoundingInfo = function () {
  7609. if (this._masterMesh) {
  7610. return this._masterMesh.getBoundingInfo();
  7611. }
  7612. if (!this._boundingInfo) {
  7613. this._updateBoundingInfo();
  7614. }
  7615. return this._boundingInfo;
  7616. };
  7617. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7618. get: function () {
  7619. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. AbstractMesh.prototype._preActivate = function () {
  7625. };
  7626. AbstractMesh.prototype._activate = function (renderId) {
  7627. this._renderId = renderId;
  7628. };
  7629. AbstractMesh.prototype.getWorldMatrix = function () {
  7630. if (this._masterMesh) {
  7631. return this._masterMesh.getWorldMatrix();
  7632. }
  7633. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7634. this.computeWorldMatrix();
  7635. }
  7636. return this._worldMatrix;
  7637. };
  7638. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7639. get: function () {
  7640. return this._worldMatrix;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7646. get: function () {
  7647. return this._absolutePosition;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7653. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7654. this.computeWorldMatrix(true);
  7655. this._isWorldMatrixFrozen = true;
  7656. };
  7657. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7658. this._isWorldMatrixFrozen = false;
  7659. this.computeWorldMatrix(true);
  7660. };
  7661. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7662. get: function () {
  7663. return this._isWorldMatrixFrozen;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7669. axis.normalize();
  7670. if (!this.rotationQuaternion) {
  7671. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7672. this.rotation = BABYLON.Vector3.Zero();
  7673. }
  7674. var rotationQuaternion;
  7675. if (!space || space === BABYLON.Space.LOCAL) {
  7676. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7677. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7678. }
  7679. else {
  7680. if (this.parent) {
  7681. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7682. invertParentWorldMatrix.invert();
  7683. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7684. }
  7685. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7686. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7687. }
  7688. };
  7689. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7690. var displacementVector = axis.scale(distance);
  7691. if (!space || space === BABYLON.Space.LOCAL) {
  7692. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7693. this.setPositionWithLocalVector(tempV3);
  7694. }
  7695. else {
  7696. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7697. }
  7698. };
  7699. AbstractMesh.prototype.getAbsolutePosition = function () {
  7700. this.computeWorldMatrix();
  7701. return this._absolutePosition;
  7702. };
  7703. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7704. if (!absolutePosition) {
  7705. return;
  7706. }
  7707. var absolutePositionX;
  7708. var absolutePositionY;
  7709. var absolutePositionZ;
  7710. if (absolutePosition.x === undefined) {
  7711. if (arguments.length < 3) {
  7712. return;
  7713. }
  7714. absolutePositionX = arguments[0];
  7715. absolutePositionY = arguments[1];
  7716. absolutePositionZ = arguments[2];
  7717. }
  7718. else {
  7719. absolutePositionX = absolutePosition.x;
  7720. absolutePositionY = absolutePosition.y;
  7721. absolutePositionZ = absolutePosition.z;
  7722. }
  7723. if (this.parent) {
  7724. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7725. invertParentWorldMatrix.invert();
  7726. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7727. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7728. }
  7729. else {
  7730. this.position.x = absolutePositionX;
  7731. this.position.y = absolutePositionY;
  7732. this.position.z = absolutePositionZ;
  7733. }
  7734. };
  7735. // ================================== Point of View Movement =================================
  7736. /**
  7737. * Perform relative position change from the point of view of behind the front of the mesh.
  7738. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7739. * Supports definition of mesh facing forward or backward.
  7740. * @param {number} amountRight
  7741. * @param {number} amountUp
  7742. * @param {number} amountForward
  7743. */
  7744. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7745. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7746. };
  7747. /**
  7748. * Calculate relative position change from the point of view of behind the front of the mesh.
  7749. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7750. * Supports definition of mesh facing forward or backward.
  7751. * @param {number} amountRight
  7752. * @param {number} amountUp
  7753. * @param {number} amountForward
  7754. */
  7755. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7756. var rotMatrix = new BABYLON.Matrix();
  7757. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7758. rotQuaternion.toRotationMatrix(rotMatrix);
  7759. var translationDelta = BABYLON.Vector3.Zero();
  7760. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7762. return translationDelta;
  7763. };
  7764. // ================================== Point of View Rotation =================================
  7765. /**
  7766. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7767. * Supports definition of mesh facing forward or backward.
  7768. * @param {number} flipBack
  7769. * @param {number} twirlClockwise
  7770. * @param {number} tiltRight
  7771. */
  7772. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7773. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7774. };
  7775. /**
  7776. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7777. * Supports definition of mesh facing forward or backward.
  7778. * @param {number} flipBack
  7779. * @param {number} twirlClockwise
  7780. * @param {number} tiltRight
  7781. */
  7782. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7783. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7784. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7785. };
  7786. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7787. this._pivotMatrix = matrix;
  7788. this._cache.pivotMatrixUpdated = true;
  7789. };
  7790. AbstractMesh.prototype.getPivotMatrix = function () {
  7791. return this._pivotMatrix;
  7792. };
  7793. AbstractMesh.prototype._isSynchronized = function () {
  7794. if (this._isDirty) {
  7795. return false;
  7796. }
  7797. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7798. return false;
  7799. if (this._cache.pivotMatrixUpdated) {
  7800. return false;
  7801. }
  7802. if (this.infiniteDistance) {
  7803. return false;
  7804. }
  7805. if (!this._cache.position.equals(this.position))
  7806. return false;
  7807. if (this.rotationQuaternion) {
  7808. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7809. return false;
  7810. }
  7811. else {
  7812. if (!this._cache.rotation.equals(this.rotation))
  7813. return false;
  7814. }
  7815. if (!this._cache.scaling.equals(this.scaling))
  7816. return false;
  7817. return true;
  7818. };
  7819. AbstractMesh.prototype._initCache = function () {
  7820. _super.prototype._initCache.call(this);
  7821. this._cache.localMatrixUpdated = false;
  7822. this._cache.position = BABYLON.Vector3.Zero();
  7823. this._cache.scaling = BABYLON.Vector3.Zero();
  7824. this._cache.rotation = BABYLON.Vector3.Zero();
  7825. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7826. };
  7827. AbstractMesh.prototype.markAsDirty = function (property) {
  7828. if (property === "rotation") {
  7829. this.rotationQuaternion = null;
  7830. }
  7831. this._currentRenderId = Number.MAX_VALUE;
  7832. this._isDirty = true;
  7833. };
  7834. AbstractMesh.prototype._updateBoundingInfo = function () {
  7835. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7836. this._boundingInfo._update(this.worldMatrixFromCache);
  7837. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7838. };
  7839. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7840. if (!this.subMeshes) {
  7841. return;
  7842. }
  7843. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7844. var subMesh = this.subMeshes[subIndex];
  7845. subMesh.updateBoundingInfo(matrix);
  7846. }
  7847. };
  7848. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7849. if (this._isWorldMatrixFrozen) {
  7850. return this._worldMatrix;
  7851. }
  7852. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7853. return this._worldMatrix;
  7854. }
  7855. this._cache.position.copyFrom(this.position);
  7856. this._cache.scaling.copyFrom(this.scaling);
  7857. this._cache.pivotMatrixUpdated = false;
  7858. this._currentRenderId = this.getScene().getRenderId();
  7859. this._isDirty = false;
  7860. // Scaling
  7861. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7862. // Rotation
  7863. if (this.rotationQuaternion) {
  7864. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7865. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7866. }
  7867. else {
  7868. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7869. this._cache.rotation.copyFrom(this.rotation);
  7870. }
  7871. // Translation
  7872. if (this.infiniteDistance && !this.parent) {
  7873. var camera = this.getScene().activeCamera;
  7874. if (camera) {
  7875. var cameraWorldMatrix = camera.getWorldMatrix();
  7876. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7877. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7878. }
  7879. }
  7880. else {
  7881. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7882. }
  7883. // Composing transformations
  7884. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7885. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7886. // Billboarding
  7887. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7888. var localPosition = this.position.clone();
  7889. var zero = this.getScene().activeCamera.globalPosition.clone();
  7890. if (this.parent && this.parent.position) {
  7891. localPosition.addInPlace(this.parent.position);
  7892. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7893. }
  7894. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7895. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7896. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7897. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7898. zero.y = localPosition.y + 0.001;
  7899. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7900. zero.z = localPosition.z + 0.001;
  7901. }
  7902. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7903. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7904. this._localBillboard.invert();
  7905. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7906. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7907. }
  7908. // Local world
  7909. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7910. // Parent
  7911. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7912. this._markSyncedWithParent();
  7913. if (this._meshToBoneReferal) {
  7914. if (!this._localMeshReferalTransform) {
  7915. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7916. }
  7917. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7918. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7919. }
  7920. else {
  7921. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7922. }
  7923. }
  7924. else {
  7925. this._worldMatrix.copyFrom(this._localWorld);
  7926. }
  7927. // Bounding info
  7928. this._updateBoundingInfo();
  7929. // Absolute position
  7930. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7931. // Callbacks
  7932. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7933. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7934. }
  7935. return this._worldMatrix;
  7936. };
  7937. /**
  7938. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7939. * @param func: callback function to add
  7940. */
  7941. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7942. this._onAfterWorldMatrixUpdate.push(func);
  7943. };
  7944. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7945. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7946. if (index > -1) {
  7947. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7948. }
  7949. };
  7950. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7951. this.computeWorldMatrix();
  7952. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7953. };
  7954. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7955. this.computeWorldMatrix();
  7956. var invLocalWorldMatrix = this._localWorld.clone();
  7957. invLocalWorldMatrix.invert();
  7958. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7959. };
  7960. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7961. this.computeWorldMatrix(true);
  7962. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7963. };
  7964. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7965. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7966. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7967. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7968. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7969. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7970. /// <returns>Mesh oriented towards targetMesh</returns>
  7971. yawCor = yawCor || 0; // default to zero if undefined
  7972. pitchCor = pitchCor || 0;
  7973. rollCor = rollCor || 0;
  7974. var dv = targetPoint.subtract(this.position);
  7975. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7976. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7977. var pitch = Math.atan2(dv.y, len);
  7978. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7979. };
  7980. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7981. this._meshToBoneReferal = affectedMesh;
  7982. this.parent = bone;
  7983. if (bone.getWorldMatrix().determinant() < 0) {
  7984. this.scalingDeterminant *= -1;
  7985. }
  7986. };
  7987. AbstractMesh.prototype.detachFromBone = function () {
  7988. if (this.parent.getWorldMatrix().determinant() < 0) {
  7989. this.scalingDeterminant *= -1;
  7990. }
  7991. this._meshToBoneReferal = null;
  7992. this.parent = null;
  7993. };
  7994. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7995. return this._boundingInfo.isInFrustum(frustumPlanes);
  7996. };
  7997. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7998. if (!camera) {
  7999. camera = this.getScene().activeCamera;
  8000. }
  8001. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8002. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8003. return false;
  8004. }
  8005. return true;
  8006. };
  8007. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8008. if (!this._boundingInfo || !mesh._boundingInfo) {
  8009. return false;
  8010. }
  8011. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8012. };
  8013. AbstractMesh.prototype.intersectsPoint = function (point) {
  8014. if (!this._boundingInfo) {
  8015. return false;
  8016. }
  8017. return this._boundingInfo.intersectsPoint(point);
  8018. };
  8019. // Physics
  8020. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8021. var physicsEngine = this.getScene().getPhysicsEngine();
  8022. if (!physicsEngine) {
  8023. return null;
  8024. }
  8025. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8026. if (impostor.impostor) {
  8027. // Old API
  8028. options = impostor;
  8029. impostor = impostor.impostor;
  8030. }
  8031. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8032. physicsEngine._unregisterMesh(this);
  8033. return null;
  8034. }
  8035. if (!options) {
  8036. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8037. }
  8038. else {
  8039. if (!options.mass && options.mass !== 0)
  8040. options.mass = 0;
  8041. if (!options.friction && options.friction !== 0)
  8042. options.friction = 0.2;
  8043. if (!options.restitution && options.restitution !== 0)
  8044. options.restitution = 0.2;
  8045. }
  8046. this._physicImpostor = impostor;
  8047. this._physicsMass = options.mass;
  8048. this._physicsFriction = options.friction;
  8049. this._physicRestitution = options.restitution;
  8050. return physicsEngine._registerMesh(this, impostor, options);
  8051. };
  8052. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8053. if (!this._physicImpostor) {
  8054. return BABYLON.PhysicsEngine.NoImpostor;
  8055. }
  8056. return this._physicImpostor;
  8057. };
  8058. AbstractMesh.prototype.getPhysicsMass = function () {
  8059. if (!this._physicsMass) {
  8060. return 0;
  8061. }
  8062. return this._physicsMass;
  8063. };
  8064. AbstractMesh.prototype.getPhysicsFriction = function () {
  8065. if (!this._physicsFriction) {
  8066. return 0;
  8067. }
  8068. return this._physicsFriction;
  8069. };
  8070. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8071. if (!this._physicRestitution) {
  8072. return 0;
  8073. }
  8074. return this._physicRestitution;
  8075. };
  8076. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8077. if (!camera) {
  8078. camera = this.getScene().activeCamera;
  8079. }
  8080. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8081. };
  8082. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8083. if (!camera) {
  8084. camera = this.getScene().activeCamera;
  8085. }
  8086. return this.absolutePosition.subtract(camera.position).length();
  8087. };
  8088. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8089. if (!this._physicImpostor) {
  8090. return;
  8091. }
  8092. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8093. };
  8094. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8095. if (!this._physicImpostor) {
  8096. return;
  8097. }
  8098. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8099. };
  8100. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8101. if (!this._physicImpostor) {
  8102. return;
  8103. }
  8104. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8105. };
  8106. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8107. // Collisions
  8108. get: function () {
  8109. return this._checkCollisions;
  8110. },
  8111. set: function (collisionEnabled) {
  8112. this._checkCollisions = collisionEnabled;
  8113. if (this.getScene().workerCollisions) {
  8114. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8115. }
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8121. var globalPosition = this.getAbsolutePosition();
  8122. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8123. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8124. this._collider.radius = this.ellipsoid;
  8125. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8126. };
  8127. // Submeshes octree
  8128. /**
  8129. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8130. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8131. */
  8132. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8133. if (maxCapacity === void 0) { maxCapacity = 64; }
  8134. if (maxDepth === void 0) { maxDepth = 2; }
  8135. if (!this._submeshesOctree) {
  8136. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8137. }
  8138. this.computeWorldMatrix(true);
  8139. // Update octree
  8140. var bbox = this.getBoundingInfo().boundingBox;
  8141. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8142. return this._submeshesOctree;
  8143. };
  8144. // Collisions
  8145. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8146. this._generatePointsArray();
  8147. // Transformation
  8148. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8149. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8150. subMesh._lastColliderWorldVertices = [];
  8151. subMesh._trianglePlanes = [];
  8152. var start = subMesh.verticesStart;
  8153. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8154. for (var i = start; i < end; i++) {
  8155. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8156. }
  8157. }
  8158. // Collide
  8159. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8160. if (collider.collisionFound) {
  8161. collider.collidedMesh = this;
  8162. }
  8163. };
  8164. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8165. var subMeshes;
  8166. var len;
  8167. // Octrees
  8168. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8169. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8170. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8171. len = intersections.length;
  8172. subMeshes = intersections.data;
  8173. }
  8174. else {
  8175. subMeshes = this.subMeshes;
  8176. len = subMeshes.length;
  8177. }
  8178. for (var index = 0; index < len; index++) {
  8179. var subMesh = subMeshes[index];
  8180. // Bounding test
  8181. if (len > 1 && !subMesh._checkCollision(collider))
  8182. continue;
  8183. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8184. }
  8185. };
  8186. AbstractMesh.prototype._checkCollision = function (collider) {
  8187. // Bounding box test
  8188. if (!this._boundingInfo._checkCollision(collider))
  8189. return;
  8190. // Transformation matrix
  8191. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8192. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8193. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8194. };
  8195. // Picking
  8196. AbstractMesh.prototype._generatePointsArray = function () {
  8197. return false;
  8198. };
  8199. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8200. var pickingInfo = new BABYLON.PickingInfo();
  8201. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8202. return pickingInfo;
  8203. }
  8204. if (!this._generatePointsArray()) {
  8205. return pickingInfo;
  8206. }
  8207. var intersectInfo = null;
  8208. // Octrees
  8209. var subMeshes;
  8210. var len;
  8211. if (this._submeshesOctree && this.useOctreeForPicking) {
  8212. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8213. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8214. len = intersections.length;
  8215. subMeshes = intersections.data;
  8216. }
  8217. else {
  8218. subMeshes = this.subMeshes;
  8219. len = subMeshes.length;
  8220. }
  8221. for (var index = 0; index < len; index++) {
  8222. var subMesh = subMeshes[index];
  8223. // Bounding test
  8224. if (len > 1 && !subMesh.canIntersects(ray))
  8225. continue;
  8226. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8227. if (currentIntersectInfo) {
  8228. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8229. intersectInfo = currentIntersectInfo;
  8230. intersectInfo.subMeshId = index;
  8231. if (fastCheck) {
  8232. break;
  8233. }
  8234. }
  8235. }
  8236. }
  8237. if (intersectInfo) {
  8238. // Get picked point
  8239. var world = this.getWorldMatrix();
  8240. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8241. var direction = ray.direction.clone();
  8242. direction = direction.scale(intersectInfo.distance);
  8243. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8244. var pickedPoint = worldOrigin.add(worldDirection);
  8245. // Return result
  8246. pickingInfo.hit = true;
  8247. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8248. pickingInfo.pickedPoint = pickedPoint;
  8249. pickingInfo.pickedMesh = this;
  8250. pickingInfo.bu = intersectInfo.bu;
  8251. pickingInfo.bv = intersectInfo.bv;
  8252. pickingInfo.faceId = intersectInfo.faceId;
  8253. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8254. return pickingInfo;
  8255. }
  8256. return pickingInfo;
  8257. };
  8258. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8259. return null;
  8260. };
  8261. AbstractMesh.prototype.releaseSubMeshes = function () {
  8262. if (this.subMeshes) {
  8263. while (this.subMeshes.length) {
  8264. this.subMeshes[0].dispose();
  8265. }
  8266. }
  8267. else {
  8268. this.subMeshes = new Array();
  8269. }
  8270. };
  8271. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8272. var index;
  8273. // Animations
  8274. this.getScene().stopAnimation(this);
  8275. // Physics
  8276. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8277. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8278. }
  8279. // Intersections in progress
  8280. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8281. var other = this._intersectionsInProgress[index];
  8282. var pos = other._intersectionsInProgress.indexOf(this);
  8283. other._intersectionsInProgress.splice(pos, 1);
  8284. }
  8285. this._intersectionsInProgress = [];
  8286. // Edges
  8287. if (this._edgesRenderer) {
  8288. this._edgesRenderer.dispose();
  8289. this._edgesRenderer = null;
  8290. }
  8291. // SubMeshes
  8292. this.releaseSubMeshes();
  8293. // Remove from scene
  8294. this.getScene().removeMesh(this);
  8295. if (!doNotRecurse) {
  8296. // Particles
  8297. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8298. if (this.getScene().particleSystems[index].emitter === this) {
  8299. this.getScene().particleSystems[index].dispose();
  8300. index--;
  8301. }
  8302. }
  8303. // Children
  8304. var objects = this.getScene().meshes.slice(0);
  8305. for (index = 0; index < objects.length; index++) {
  8306. if (objects[index].parent === this) {
  8307. objects[index].dispose();
  8308. }
  8309. }
  8310. }
  8311. else {
  8312. for (index = 0; index < this.getScene().meshes.length; index++) {
  8313. var obj = this.getScene().meshes[index];
  8314. if (obj.parent === this) {
  8315. obj.parent = null;
  8316. obj.computeWorldMatrix(true);
  8317. }
  8318. }
  8319. }
  8320. this._onAfterWorldMatrixUpdate = [];
  8321. this._isDisposed = true;
  8322. // Callback
  8323. if (this.onDispose) {
  8324. this.onDispose();
  8325. }
  8326. };
  8327. // Statics
  8328. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8329. AbstractMesh._BILLBOARDMODE_X = 1;
  8330. AbstractMesh._BILLBOARDMODE_Y = 2;
  8331. AbstractMesh._BILLBOARDMODE_Z = 4;
  8332. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8333. return AbstractMesh;
  8334. })(BABYLON.Node);
  8335. BABYLON.AbstractMesh = AbstractMesh;
  8336. })(BABYLON || (BABYLON = {}));
  8337. var BABYLON;
  8338. (function (BABYLON) {
  8339. var Light = (function (_super) {
  8340. __extends(Light, _super);
  8341. function Light(name, scene) {
  8342. _super.call(this, name, scene);
  8343. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8344. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8345. this.intensity = 1.0;
  8346. this.range = Number.MAX_VALUE;
  8347. this.includeOnlyWithLayerMask = 0;
  8348. this.includedOnlyMeshes = new Array();
  8349. this.excludedMeshes = new Array();
  8350. this.excludeWithLayerMask = 0;
  8351. this._excludedMeshesIds = new Array();
  8352. this._includedOnlyMeshesIds = new Array();
  8353. scene.addLight(this);
  8354. }
  8355. Light.prototype.getShadowGenerator = function () {
  8356. return this._shadowGenerator;
  8357. };
  8358. Light.prototype.getAbsolutePosition = function () {
  8359. return BABYLON.Vector3.Zero();
  8360. };
  8361. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8362. };
  8363. Light.prototype._getWorldMatrix = function () {
  8364. return BABYLON.Matrix.Identity();
  8365. };
  8366. Light.prototype.canAffectMesh = function (mesh) {
  8367. if (!mesh) {
  8368. return true;
  8369. }
  8370. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8371. return false;
  8372. }
  8373. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8374. return false;
  8375. }
  8376. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8377. return false;
  8378. }
  8379. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8380. return false;
  8381. }
  8382. return true;
  8383. };
  8384. Light.prototype.getWorldMatrix = function () {
  8385. this._currentRenderId = this.getScene().getRenderId();
  8386. var worldMatrix = this._getWorldMatrix();
  8387. if (this.parent && this.parent.getWorldMatrix) {
  8388. if (!this._parentedWorldMatrix) {
  8389. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8390. }
  8391. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8392. this._markSyncedWithParent();
  8393. return this._parentedWorldMatrix;
  8394. }
  8395. return worldMatrix;
  8396. };
  8397. Light.prototype.dispose = function () {
  8398. if (this._shadowGenerator) {
  8399. this._shadowGenerator.dispose();
  8400. this._shadowGenerator = null;
  8401. }
  8402. // Animations
  8403. this.getScene().stopAnimation(this);
  8404. // Remove from scene
  8405. this.getScene().removeLight(this);
  8406. };
  8407. return Light;
  8408. })(BABYLON.Node);
  8409. BABYLON.Light = Light;
  8410. })(BABYLON || (BABYLON = {}));
  8411. var BABYLON;
  8412. (function (BABYLON) {
  8413. var PointLight = (function (_super) {
  8414. __extends(PointLight, _super);
  8415. function PointLight(name, position, scene) {
  8416. _super.call(this, name, scene);
  8417. this.position = position;
  8418. }
  8419. PointLight.prototype.getAbsolutePosition = function () {
  8420. return this.transformedPosition ? this.transformedPosition : this.position;
  8421. };
  8422. PointLight.prototype.computeTransformedPosition = function () {
  8423. if (this.parent && this.parent.getWorldMatrix) {
  8424. if (!this.transformedPosition) {
  8425. this.transformedPosition = BABYLON.Vector3.Zero();
  8426. }
  8427. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8428. return true;
  8429. }
  8430. return false;
  8431. };
  8432. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8433. if (this.parent && this.parent.getWorldMatrix) {
  8434. this.computeTransformedPosition();
  8435. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8436. return;
  8437. }
  8438. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8439. };
  8440. PointLight.prototype.needCube = function () {
  8441. return true;
  8442. };
  8443. PointLight.prototype.supportsVSM = function () {
  8444. return false;
  8445. };
  8446. PointLight.prototype.needRefreshPerFrame = function () {
  8447. return false;
  8448. };
  8449. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8450. switch (faceIndex) {
  8451. case 0:
  8452. return new BABYLON.Vector3(1, 0, 0);
  8453. case 1:
  8454. return new BABYLON.Vector3(-1, 0, 0);
  8455. case 2:
  8456. return new BABYLON.Vector3(0, -1, 0);
  8457. case 3:
  8458. return new BABYLON.Vector3(0, 1, 0);
  8459. case 4:
  8460. return new BABYLON.Vector3(0, 0, 1);
  8461. case 5:
  8462. return new BABYLON.Vector3(0, 0, -1);
  8463. }
  8464. return BABYLON.Vector3.Zero();
  8465. };
  8466. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8467. var activeCamera = this.getScene().activeCamera;
  8468. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8469. };
  8470. PointLight.prototype._getWorldMatrix = function () {
  8471. if (!this._worldMatrix) {
  8472. this._worldMatrix = BABYLON.Matrix.Identity();
  8473. }
  8474. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8475. return this._worldMatrix;
  8476. };
  8477. return PointLight;
  8478. })(BABYLON.Light);
  8479. BABYLON.PointLight = PointLight;
  8480. })(BABYLON || (BABYLON = {}));
  8481. var BABYLON;
  8482. (function (BABYLON) {
  8483. var SpotLight = (function (_super) {
  8484. __extends(SpotLight, _super);
  8485. function SpotLight(name, position, direction, angle, exponent, scene) {
  8486. _super.call(this, name, scene);
  8487. this.position = position;
  8488. this.direction = direction;
  8489. this.angle = angle;
  8490. this.exponent = exponent;
  8491. }
  8492. SpotLight.prototype.getAbsolutePosition = function () {
  8493. return this.transformedPosition ? this.transformedPosition : this.position;
  8494. };
  8495. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8496. var activeCamera = this.getScene().activeCamera;
  8497. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8498. };
  8499. SpotLight.prototype.needCube = function () {
  8500. return false;
  8501. };
  8502. SpotLight.prototype.supportsVSM = function () {
  8503. return true;
  8504. };
  8505. SpotLight.prototype.needRefreshPerFrame = function () {
  8506. return false;
  8507. };
  8508. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8509. return this.direction;
  8510. };
  8511. SpotLight.prototype.setDirectionToTarget = function (target) {
  8512. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8513. return this.direction;
  8514. };
  8515. SpotLight.prototype.computeTransformedPosition = function () {
  8516. if (this.parent && this.parent.getWorldMatrix) {
  8517. if (!this.transformedPosition) {
  8518. this.transformedPosition = BABYLON.Vector3.Zero();
  8519. }
  8520. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8521. return true;
  8522. }
  8523. return false;
  8524. };
  8525. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8526. var normalizeDirection;
  8527. if (this.parent && this.parent.getWorldMatrix) {
  8528. if (!this._transformedDirection) {
  8529. this._transformedDirection = BABYLON.Vector3.Zero();
  8530. }
  8531. this.computeTransformedPosition();
  8532. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8533. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8534. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8535. }
  8536. else {
  8537. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8538. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8539. }
  8540. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8541. };
  8542. SpotLight.prototype._getWorldMatrix = function () {
  8543. if (!this._worldMatrix) {
  8544. this._worldMatrix = BABYLON.Matrix.Identity();
  8545. }
  8546. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8547. return this._worldMatrix;
  8548. };
  8549. return SpotLight;
  8550. })(BABYLON.Light);
  8551. BABYLON.SpotLight = SpotLight;
  8552. })(BABYLON || (BABYLON = {}));
  8553. var BABYLON;
  8554. (function (BABYLON) {
  8555. var HemisphericLight = (function (_super) {
  8556. __extends(HemisphericLight, _super);
  8557. function HemisphericLight(name, direction, scene) {
  8558. _super.call(this, name, scene);
  8559. this.direction = direction;
  8560. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8561. }
  8562. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8563. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8564. return this.direction;
  8565. };
  8566. HemisphericLight.prototype.getShadowGenerator = function () {
  8567. return null;
  8568. };
  8569. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8570. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8571. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8572. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8573. };
  8574. HemisphericLight.prototype._getWorldMatrix = function () {
  8575. if (!this._worldMatrix) {
  8576. this._worldMatrix = BABYLON.Matrix.Identity();
  8577. }
  8578. return this._worldMatrix;
  8579. };
  8580. return HemisphericLight;
  8581. })(BABYLON.Light);
  8582. BABYLON.HemisphericLight = HemisphericLight;
  8583. })(BABYLON || (BABYLON = {}));
  8584. var BABYLON;
  8585. (function (BABYLON) {
  8586. var DirectionalLight = (function (_super) {
  8587. __extends(DirectionalLight, _super);
  8588. function DirectionalLight(name, direction, scene) {
  8589. _super.call(this, name, scene);
  8590. this.direction = direction;
  8591. this.shadowOrthoScale = 0.5;
  8592. this.autoUpdateExtends = true;
  8593. // Cache
  8594. this._orthoLeft = Number.MAX_VALUE;
  8595. this._orthoRight = Number.MIN_VALUE;
  8596. this._orthoTop = Number.MIN_VALUE;
  8597. this._orthoBottom = Number.MAX_VALUE;
  8598. this.position = direction.scale(-1);
  8599. }
  8600. DirectionalLight.prototype.getAbsolutePosition = function () {
  8601. return this.transformedPosition ? this.transformedPosition : this.position;
  8602. };
  8603. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8604. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8605. return this.direction;
  8606. };
  8607. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8608. var activeCamera = this.getScene().activeCamera;
  8609. // Check extends
  8610. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8611. var tempVector3 = BABYLON.Vector3.Zero();
  8612. this._orthoLeft = Number.MAX_VALUE;
  8613. this._orthoRight = Number.MIN_VALUE;
  8614. this._orthoTop = Number.MIN_VALUE;
  8615. this._orthoBottom = Number.MAX_VALUE;
  8616. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8617. var mesh = renderList[meshIndex];
  8618. if (!mesh) {
  8619. continue;
  8620. }
  8621. var boundingInfo = mesh.getBoundingInfo();
  8622. if (!boundingInfo) {
  8623. continue;
  8624. }
  8625. var boundingBox = boundingInfo.boundingBox;
  8626. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8627. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8628. if (tempVector3.x < this._orthoLeft)
  8629. this._orthoLeft = tempVector3.x;
  8630. if (tempVector3.y < this._orthoBottom)
  8631. this._orthoBottom = tempVector3.y;
  8632. if (tempVector3.x > this._orthoRight)
  8633. this._orthoRight = tempVector3.x;
  8634. if (tempVector3.y > this._orthoTop)
  8635. this._orthoTop = tempVector3.y;
  8636. }
  8637. }
  8638. }
  8639. var xOffset = this._orthoRight - this._orthoLeft;
  8640. var yOffset = this._orthoTop - this._orthoBottom;
  8641. 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);
  8642. };
  8643. DirectionalLight.prototype.supportsVSM = function () {
  8644. return true;
  8645. };
  8646. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8647. return true;
  8648. };
  8649. DirectionalLight.prototype.needCube = function () {
  8650. return false;
  8651. };
  8652. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8653. return this.direction;
  8654. };
  8655. DirectionalLight.prototype.computeTransformedPosition = function () {
  8656. if (this.parent && this.parent.getWorldMatrix) {
  8657. if (!this.transformedPosition) {
  8658. this.transformedPosition = BABYLON.Vector3.Zero();
  8659. }
  8660. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8661. return true;
  8662. }
  8663. return false;
  8664. };
  8665. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8666. if (this.parent && this.parent.getWorldMatrix) {
  8667. if (!this._transformedDirection) {
  8668. this._transformedDirection = BABYLON.Vector3.Zero();
  8669. }
  8670. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8671. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8672. return;
  8673. }
  8674. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8675. };
  8676. DirectionalLight.prototype._getWorldMatrix = function () {
  8677. if (!this._worldMatrix) {
  8678. this._worldMatrix = BABYLON.Matrix.Identity();
  8679. }
  8680. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8681. return this._worldMatrix;
  8682. };
  8683. return DirectionalLight;
  8684. })(BABYLON.Light);
  8685. BABYLON.DirectionalLight = DirectionalLight;
  8686. })(BABYLON || (BABYLON = {}));
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. var ShadowGenerator = (function () {
  8690. function ShadowGenerator(mapSize, light) {
  8691. var _this = this;
  8692. // Members
  8693. this._filter = ShadowGenerator.FILTER_NONE;
  8694. this.blurScale = 2;
  8695. this._blurBoxOffset = 0;
  8696. this._bias = 0.00005;
  8697. this._lightDirection = BABYLON.Vector3.Zero();
  8698. this._darkness = 0;
  8699. this._transparencyShadow = false;
  8700. this._viewMatrix = BABYLON.Matrix.Zero();
  8701. this._projectionMatrix = BABYLON.Matrix.Zero();
  8702. this._transformMatrix = BABYLON.Matrix.Zero();
  8703. this._worldViewProjection = BABYLON.Matrix.Zero();
  8704. this._currentFaceIndex = 0;
  8705. this._currentFaceIndexCache = 0;
  8706. this._light = light;
  8707. this._scene = light.getScene();
  8708. this._mapSize = mapSize;
  8709. light._shadowGenerator = this;
  8710. // Render target
  8711. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8712. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8713. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8714. this._shadowMap.anisotropicFilteringLevel = 1;
  8715. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8716. this._shadowMap.renderParticles = false;
  8717. this._shadowMap.onBeforeRender = function (faceIndex) {
  8718. _this._currentFaceIndex = faceIndex;
  8719. };
  8720. this._shadowMap.onAfterUnbind = function () {
  8721. if (!_this.useBlurVarianceShadowMap) {
  8722. return;
  8723. }
  8724. if (!_this._shadowMap2) {
  8725. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8726. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8727. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8728. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8729. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8730. _this._downSamplePostprocess.onApply = function (effect) {
  8731. effect.setTexture("textureSampler", _this._shadowMap);
  8732. };
  8733. _this.blurBoxOffset = 1;
  8734. }
  8735. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8736. };
  8737. // Custom render function
  8738. var renderSubMesh = function (subMesh) {
  8739. var mesh = subMesh.getRenderingMesh();
  8740. var scene = _this._scene;
  8741. var engine = scene.getEngine();
  8742. // Culling
  8743. engine.setState(subMesh.getMaterial().backFaceCulling);
  8744. // Managing instances
  8745. var batch = mesh._getInstancesRenderList(subMesh._id);
  8746. if (batch.mustReturn) {
  8747. return;
  8748. }
  8749. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8750. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8751. engine.enableEffect(_this._effect);
  8752. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8753. var material = subMesh.getMaterial();
  8754. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8755. // Alpha test
  8756. if (material && material.needAlphaTesting()) {
  8757. var alphaTexture = material.getAlphaTestTexture();
  8758. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8759. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8760. }
  8761. // Bones
  8762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8763. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8764. }
  8765. // Draw
  8766. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8767. }
  8768. else {
  8769. // Need to reset refresh rate of the shadowMap
  8770. _this._shadowMap.resetRefreshCounter();
  8771. }
  8772. };
  8773. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8774. var index;
  8775. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8776. renderSubMesh(opaqueSubMeshes.data[index]);
  8777. }
  8778. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8779. renderSubMesh(alphaTestSubMeshes.data[index]);
  8780. }
  8781. if (_this._transparencyShadow) {
  8782. for (index = 0; index < transparentSubMeshes.length; index++) {
  8783. renderSubMesh(transparentSubMeshes.data[index]);
  8784. }
  8785. }
  8786. };
  8787. this._shadowMap.onClear = function (engine) {
  8788. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8789. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8790. }
  8791. else {
  8792. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8793. }
  8794. };
  8795. }
  8796. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8797. // Static
  8798. get: function () {
  8799. return ShadowGenerator._FILTER_NONE;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8805. get: function () {
  8806. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8812. get: function () {
  8813. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8819. get: function () {
  8820. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8821. },
  8822. enumerable: true,
  8823. configurable: true
  8824. });
  8825. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8826. get: function () {
  8827. return this._bias;
  8828. },
  8829. set: function (bias) {
  8830. this._bias = bias;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8836. get: function () {
  8837. return this._blurBoxOffset;
  8838. },
  8839. set: function (value) {
  8840. var _this = this;
  8841. if (this._blurBoxOffset === value) {
  8842. return;
  8843. }
  8844. this._blurBoxOffset = value;
  8845. if (this._boxBlurPostprocess) {
  8846. this._boxBlurPostprocess.dispose();
  8847. }
  8848. 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);
  8849. this._boxBlurPostprocess.onApply = function (effect) {
  8850. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8851. };
  8852. },
  8853. enumerable: true,
  8854. configurable: true
  8855. });
  8856. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8857. get: function () {
  8858. return this._filter;
  8859. },
  8860. set: function (value) {
  8861. if (this._filter === value) {
  8862. return;
  8863. }
  8864. this._filter = value;
  8865. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8866. this._shadowMap.anisotropicFilteringLevel = 16;
  8867. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8868. }
  8869. else {
  8870. this._shadowMap.anisotropicFilteringLevel = 1;
  8871. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8872. }
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8878. get: function () {
  8879. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8880. },
  8881. set: function (value) {
  8882. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8888. get: function () {
  8889. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8890. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8891. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8892. },
  8893. set: function (value) {
  8894. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8895. },
  8896. enumerable: true,
  8897. configurable: true
  8898. });
  8899. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8900. get: function () {
  8901. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8902. },
  8903. set: function (value) {
  8904. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8905. },
  8906. enumerable: true,
  8907. configurable: true
  8908. });
  8909. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8910. var defines = [];
  8911. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8912. defines.push("#define VSM");
  8913. }
  8914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8915. var mesh = subMesh.getMesh();
  8916. var material = subMesh.getMaterial();
  8917. // Alpha test
  8918. if (material && material.needAlphaTesting()) {
  8919. defines.push("#define ALPHATEST");
  8920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8921. attribs.push(BABYLON.VertexBuffer.UVKind);
  8922. defines.push("#define UV1");
  8923. }
  8924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8925. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8926. defines.push("#define UV2");
  8927. }
  8928. }
  8929. // Bones
  8930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8933. if (mesh.numBoneInfluencers > 4) {
  8934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  8935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  8936. }
  8937. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  8938. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8939. }
  8940. else {
  8941. defines.push("#define NUM_BONE_INFLUENCERS 0");
  8942. }
  8943. // Instances
  8944. if (useInstances) {
  8945. defines.push("#define INSTANCES");
  8946. attribs.push("world0");
  8947. attribs.push("world1");
  8948. attribs.push("world2");
  8949. attribs.push("world3");
  8950. }
  8951. // Get correct effect
  8952. var join = defines.join("\n");
  8953. if (this._cachedDefines !== join) {
  8954. this._cachedDefines = join;
  8955. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8956. }
  8957. return this._effect.isReady();
  8958. };
  8959. ShadowGenerator.prototype.getShadowMap = function () {
  8960. return this._shadowMap;
  8961. };
  8962. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8963. if (this._shadowMap2) {
  8964. return this._shadowMap2;
  8965. }
  8966. return this._shadowMap;
  8967. };
  8968. ShadowGenerator.prototype.getLight = function () {
  8969. return this._light;
  8970. };
  8971. // Methods
  8972. ShadowGenerator.prototype.getTransformMatrix = function () {
  8973. var scene = this._scene;
  8974. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  8975. return this._transformMatrix;
  8976. }
  8977. this._currentRenderID = scene.getRenderId();
  8978. this._currentFaceIndexCache = this._currentFaceIndex;
  8979. var lightPosition = this._light.position;
  8980. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  8981. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  8982. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8983. }
  8984. if (this._light.computeTransformedPosition()) {
  8985. lightPosition = this._light.transformedPosition;
  8986. }
  8987. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8988. this._cachedPosition = lightPosition.clone();
  8989. this._cachedDirection = this._lightDirection.clone();
  8990. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8991. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8993. }
  8994. return this._transformMatrix;
  8995. };
  8996. ShadowGenerator.prototype.getDarkness = function () {
  8997. return this._darkness;
  8998. };
  8999. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9000. if (darkness >= 1.0)
  9001. this._darkness = 1.0;
  9002. else if (darkness <= 0.0)
  9003. this._darkness = 0.0;
  9004. else
  9005. this._darkness = darkness;
  9006. };
  9007. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9008. this._transparencyShadow = hasShadow;
  9009. };
  9010. ShadowGenerator.prototype._packHalf = function (depth) {
  9011. var scale = depth * 255.0;
  9012. var fract = scale - Math.floor(scale);
  9013. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9014. };
  9015. ShadowGenerator.prototype.dispose = function () {
  9016. this._shadowMap.dispose();
  9017. if (this._shadowMap2) {
  9018. this._shadowMap2.dispose();
  9019. }
  9020. if (this._downSamplePostprocess) {
  9021. this._downSamplePostprocess.dispose();
  9022. }
  9023. if (this._boxBlurPostprocess) {
  9024. this._boxBlurPostprocess.dispose();
  9025. }
  9026. };
  9027. ShadowGenerator._FILTER_NONE = 0;
  9028. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9029. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9030. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9031. return ShadowGenerator;
  9032. })();
  9033. BABYLON.ShadowGenerator = ShadowGenerator;
  9034. })(BABYLON || (BABYLON = {}));
  9035. var BABYLON;
  9036. (function (BABYLON) {
  9037. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9038. if (boxMin.x > sphereCenter.x + sphereRadius)
  9039. return false;
  9040. if (sphereCenter.x - sphereRadius > boxMax.x)
  9041. return false;
  9042. if (boxMin.y > sphereCenter.y + sphereRadius)
  9043. return false;
  9044. if (sphereCenter.y - sphereRadius > boxMax.y)
  9045. return false;
  9046. if (boxMin.z > sphereCenter.z + sphereRadius)
  9047. return false;
  9048. if (sphereCenter.z - sphereRadius > boxMax.z)
  9049. return false;
  9050. return true;
  9051. };
  9052. var getLowestRoot = function (a, b, c, maxR) {
  9053. var determinant = b * b - 4.0 * a * c;
  9054. var result = { root: 0, found: false };
  9055. if (determinant < 0)
  9056. return result;
  9057. var sqrtD = Math.sqrt(determinant);
  9058. var r1 = (-b - sqrtD) / (2.0 * a);
  9059. var r2 = (-b + sqrtD) / (2.0 * a);
  9060. if (r1 > r2) {
  9061. var temp = r2;
  9062. r2 = r1;
  9063. r1 = temp;
  9064. }
  9065. if (r1 > 0 && r1 < maxR) {
  9066. result.root = r1;
  9067. result.found = true;
  9068. return result;
  9069. }
  9070. if (r2 > 0 && r2 < maxR) {
  9071. result.root = r2;
  9072. result.found = true;
  9073. return result;
  9074. }
  9075. return result;
  9076. };
  9077. var Collider = (function () {
  9078. function Collider() {
  9079. this.radius = new BABYLON.Vector3(1, 1, 1);
  9080. this.retry = 0;
  9081. this.basePointWorld = BABYLON.Vector3.Zero();
  9082. this.velocityWorld = BABYLON.Vector3.Zero();
  9083. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9084. this._collisionPoint = BABYLON.Vector3.Zero();
  9085. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9086. this._tempVector = BABYLON.Vector3.Zero();
  9087. this._tempVector2 = BABYLON.Vector3.Zero();
  9088. this._tempVector3 = BABYLON.Vector3.Zero();
  9089. this._tempVector4 = BABYLON.Vector3.Zero();
  9090. this._edge = BABYLON.Vector3.Zero();
  9091. this._baseToVertex = BABYLON.Vector3.Zero();
  9092. this._destinationPoint = BABYLON.Vector3.Zero();
  9093. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9094. this._displacementVector = BABYLON.Vector3.Zero();
  9095. }
  9096. // Methods
  9097. Collider.prototype._initialize = function (source, dir, e) {
  9098. this.velocity = dir;
  9099. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9100. this.basePoint = source;
  9101. source.multiplyToRef(this.radius, this.basePointWorld);
  9102. dir.multiplyToRef(this.radius, this.velocityWorld);
  9103. this.velocityWorldLength = this.velocityWorld.length();
  9104. this.epsilon = e;
  9105. this.collisionFound = false;
  9106. };
  9107. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9108. pa.subtractToRef(point, this._tempVector);
  9109. pb.subtractToRef(point, this._tempVector2);
  9110. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9111. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9112. if (d < 0)
  9113. return false;
  9114. pc.subtractToRef(point, this._tempVector3);
  9115. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9116. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9117. if (d < 0)
  9118. return false;
  9119. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9120. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9121. return d >= 0;
  9122. };
  9123. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9124. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9125. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9126. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9127. return false;
  9128. }
  9129. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9130. return false;
  9131. return true;
  9132. };
  9133. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9134. var t0;
  9135. var embeddedInPlane = false;
  9136. //defensive programming, actually not needed.
  9137. if (!trianglePlaneArray) {
  9138. trianglePlaneArray = [];
  9139. }
  9140. if (!trianglePlaneArray[faceIndex]) {
  9141. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9142. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9143. }
  9144. var trianglePlane = trianglePlaneArray[faceIndex];
  9145. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9146. return;
  9147. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9148. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9149. if (normalDotVelocity == 0) {
  9150. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9151. return;
  9152. embeddedInPlane = true;
  9153. t0 = 0;
  9154. }
  9155. else {
  9156. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9157. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9158. if (t0 > t1) {
  9159. var temp = t1;
  9160. t1 = t0;
  9161. t0 = temp;
  9162. }
  9163. if (t0 > 1.0 || t1 < 0.0)
  9164. return;
  9165. if (t0 < 0)
  9166. t0 = 0;
  9167. if (t0 > 1.0)
  9168. t0 = 1.0;
  9169. }
  9170. this._collisionPoint.copyFromFloats(0, 0, 0);
  9171. var found = false;
  9172. var t = 1.0;
  9173. if (!embeddedInPlane) {
  9174. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9175. this.velocity.scaleToRef(t0, this._tempVector);
  9176. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9177. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9178. found = true;
  9179. t = t0;
  9180. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9181. }
  9182. }
  9183. if (!found) {
  9184. var velocitySquaredLength = this.velocity.lengthSquared();
  9185. var a = velocitySquaredLength;
  9186. this.basePoint.subtractToRef(p1, this._tempVector);
  9187. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9188. var c = this._tempVector.lengthSquared() - 1.0;
  9189. var lowestRoot = getLowestRoot(a, b, c, t);
  9190. if (lowestRoot.found) {
  9191. t = lowestRoot.root;
  9192. found = true;
  9193. this._collisionPoint.copyFrom(p1);
  9194. }
  9195. this.basePoint.subtractToRef(p2, this._tempVector);
  9196. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9197. c = this._tempVector.lengthSquared() - 1.0;
  9198. lowestRoot = getLowestRoot(a, b, c, t);
  9199. if (lowestRoot.found) {
  9200. t = lowestRoot.root;
  9201. found = true;
  9202. this._collisionPoint.copyFrom(p2);
  9203. }
  9204. this.basePoint.subtractToRef(p3, this._tempVector);
  9205. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9206. c = this._tempVector.lengthSquared() - 1.0;
  9207. lowestRoot = getLowestRoot(a, b, c, t);
  9208. if (lowestRoot.found) {
  9209. t = lowestRoot.root;
  9210. found = true;
  9211. this._collisionPoint.copyFrom(p3);
  9212. }
  9213. p2.subtractToRef(p1, this._edge);
  9214. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9215. var edgeSquaredLength = this._edge.lengthSquared();
  9216. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9217. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9218. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9219. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9220. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9221. lowestRoot = getLowestRoot(a, b, c, t);
  9222. if (lowestRoot.found) {
  9223. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9224. if (f >= 0.0 && f <= 1.0) {
  9225. t = lowestRoot.root;
  9226. found = true;
  9227. this._edge.scaleInPlace(f);
  9228. p1.addToRef(this._edge, this._collisionPoint);
  9229. }
  9230. }
  9231. p3.subtractToRef(p2, this._edge);
  9232. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9233. edgeSquaredLength = this._edge.lengthSquared();
  9234. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9235. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9236. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9237. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9238. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9239. lowestRoot = getLowestRoot(a, b, c, t);
  9240. if (lowestRoot.found) {
  9241. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9242. if (f >= 0.0 && f <= 1.0) {
  9243. t = lowestRoot.root;
  9244. found = true;
  9245. this._edge.scaleInPlace(f);
  9246. p2.addToRef(this._edge, this._collisionPoint);
  9247. }
  9248. }
  9249. p1.subtractToRef(p3, this._edge);
  9250. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9251. edgeSquaredLength = this._edge.lengthSquared();
  9252. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9253. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9254. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9255. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9256. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9257. lowestRoot = getLowestRoot(a, b, c, t);
  9258. if (lowestRoot.found) {
  9259. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9260. if (f >= 0.0 && f <= 1.0) {
  9261. t = lowestRoot.root;
  9262. found = true;
  9263. this._edge.scaleInPlace(f);
  9264. p3.addToRef(this._edge, this._collisionPoint);
  9265. }
  9266. }
  9267. }
  9268. if (found) {
  9269. var distToCollision = t * this.velocity.length();
  9270. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9271. if (!this.intersectionPoint) {
  9272. this.intersectionPoint = this._collisionPoint.clone();
  9273. }
  9274. else {
  9275. this.intersectionPoint.copyFrom(this._collisionPoint);
  9276. }
  9277. this.nearestDistance = distToCollision;
  9278. this.collisionFound = true;
  9279. }
  9280. }
  9281. };
  9282. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9283. for (var i = indexStart; i < indexEnd; i += 3) {
  9284. var p1 = pts[indices[i] - decal];
  9285. var p2 = pts[indices[i + 1] - decal];
  9286. var p3 = pts[indices[i + 2] - decal];
  9287. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9288. }
  9289. };
  9290. Collider.prototype._getResponse = function (pos, vel) {
  9291. pos.addToRef(vel, this._destinationPoint);
  9292. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9293. this.basePoint.addToRef(vel, pos);
  9294. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9295. this._slidePlaneNormal.normalize();
  9296. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9297. pos.addInPlace(this._displacementVector);
  9298. this.intersectionPoint.addInPlace(this._displacementVector);
  9299. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9300. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9301. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9302. };
  9303. return Collider;
  9304. })();
  9305. BABYLON.Collider = Collider;
  9306. })(BABYLON || (BABYLON = {}));
  9307. var BABYLON;
  9308. (function (BABYLON) {
  9309. //WebWorker code will be inserted to this variable.
  9310. BABYLON.CollisionWorker = "";
  9311. (function (WorkerTaskType) {
  9312. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9313. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9314. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9315. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9316. var WorkerTaskType = BABYLON.WorkerTaskType;
  9317. (function (WorkerReplyType) {
  9318. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9319. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9320. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9321. var WorkerReplyType = BABYLON.WorkerReplyType;
  9322. var CollisionCoordinatorWorker = (function () {
  9323. function CollisionCoordinatorWorker() {
  9324. var _this = this;
  9325. this._scaledPosition = BABYLON.Vector3.Zero();
  9326. this._scaledVelocity = BABYLON.Vector3.Zero();
  9327. this.onMeshUpdated = function (mesh) {
  9328. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9329. };
  9330. this.onGeometryUpdated = function (geometry) {
  9331. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9332. };
  9333. this._afterRender = function () {
  9334. if (!_this._init)
  9335. return;
  9336. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9337. return;
  9338. }
  9339. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9340. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9341. if (_this._runningUpdated > 4) {
  9342. return;
  9343. }
  9344. ++_this._runningUpdated;
  9345. var payload = {
  9346. updatedMeshes: _this._addUpdateMeshesList,
  9347. updatedGeometries: _this._addUpdateGeometriesList,
  9348. removedGeometries: _this._toRemoveGeometryArray,
  9349. removedMeshes: _this._toRemoveMeshesArray
  9350. };
  9351. var message = {
  9352. payload: payload,
  9353. taskType: WorkerTaskType.UPDATE
  9354. };
  9355. var serializable = [];
  9356. for (var id in payload.updatedGeometries) {
  9357. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9358. //prepare transferables
  9359. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9360. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9361. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9362. }
  9363. }
  9364. _this._worker.postMessage(message, serializable);
  9365. _this._addUpdateMeshesList = {};
  9366. _this._addUpdateGeometriesList = {};
  9367. _this._toRemoveGeometryArray = [];
  9368. _this._toRemoveMeshesArray = [];
  9369. };
  9370. this._onMessageFromWorker = function (e) {
  9371. var returnData = e.data;
  9372. if (returnData.error != WorkerReplyType.SUCCESS) {
  9373. //TODO what errors can be returned from the worker?
  9374. BABYLON.Tools.Warn("error returned from worker!");
  9375. return;
  9376. }
  9377. switch (returnData.taskType) {
  9378. case WorkerTaskType.INIT:
  9379. _this._init = true;
  9380. //Update the worked with ALL of the scene's current state
  9381. _this._scene.meshes.forEach(function (mesh) {
  9382. _this.onMeshAdded(mesh);
  9383. });
  9384. _this._scene.getGeometries().forEach(function (geometry) {
  9385. _this.onGeometryAdded(geometry);
  9386. });
  9387. break;
  9388. case WorkerTaskType.UPDATE:
  9389. _this._runningUpdated--;
  9390. break;
  9391. case WorkerTaskType.COLLIDE:
  9392. _this._runningCollisionTask = false;
  9393. var returnPayload = returnData.payload;
  9394. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9395. return;
  9396. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9397. //cleanup
  9398. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9399. break;
  9400. }
  9401. };
  9402. this._collisionsCallbackArray = [];
  9403. this._init = false;
  9404. this._runningUpdated = 0;
  9405. this._runningCollisionTask = false;
  9406. this._addUpdateMeshesList = {};
  9407. this._addUpdateGeometriesList = {};
  9408. this._toRemoveGeometryArray = [];
  9409. this._toRemoveMeshesArray = [];
  9410. }
  9411. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9412. if (!this._init)
  9413. return;
  9414. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9415. return;
  9416. position.divideToRef(collider.radius, this._scaledPosition);
  9417. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9418. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9419. var payload = {
  9420. collider: {
  9421. position: this._scaledPosition.asArray(),
  9422. velocity: this._scaledVelocity.asArray(),
  9423. radius: collider.radius.asArray()
  9424. },
  9425. collisionId: collisionIndex,
  9426. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9427. maximumRetry: maximumRetry
  9428. };
  9429. var message = {
  9430. payload: payload,
  9431. taskType: WorkerTaskType.COLLIDE
  9432. };
  9433. this._worker.postMessage(message);
  9434. };
  9435. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9436. this._scene = scene;
  9437. this._scene.registerAfterRender(this._afterRender);
  9438. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9439. this._worker = new Worker(workerUrl);
  9440. this._worker.onmessage = this._onMessageFromWorker;
  9441. var message = {
  9442. payload: {},
  9443. taskType: WorkerTaskType.INIT
  9444. };
  9445. this._worker.postMessage(message);
  9446. };
  9447. CollisionCoordinatorWorker.prototype.destroy = function () {
  9448. this._scene.unregisterAfterRender(this._afterRender);
  9449. this._worker.terminate();
  9450. };
  9451. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9452. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9453. this.onMeshUpdated(mesh);
  9454. };
  9455. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9456. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9457. };
  9458. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9459. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9460. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9461. this.onGeometryUpdated(geometry);
  9462. };
  9463. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9464. this._toRemoveGeometryArray.push(geometry.id);
  9465. };
  9466. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9467. var submeshes = [];
  9468. if (mesh.subMeshes) {
  9469. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9470. return {
  9471. position: idx,
  9472. verticesStart: sm.verticesStart,
  9473. verticesCount: sm.verticesCount,
  9474. indexStart: sm.indexStart,
  9475. indexCount: sm.indexCount,
  9476. hasMaterial: !!sm.getMaterial(),
  9477. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9478. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9479. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9480. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9481. };
  9482. });
  9483. }
  9484. var geometryId = null;
  9485. if (mesh instanceof BABYLON.Mesh) {
  9486. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9487. }
  9488. else if (mesh instanceof BABYLON.InstancedMesh) {
  9489. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9490. }
  9491. return {
  9492. uniqueId: mesh.uniqueId,
  9493. id: mesh.id,
  9494. name: mesh.name,
  9495. geometryId: geometryId,
  9496. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9497. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9498. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9499. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9500. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9501. subMeshes: submeshes,
  9502. checkCollisions: mesh.checkCollisions
  9503. };
  9504. };
  9505. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9506. return {
  9507. id: geometry.id,
  9508. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9509. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9510. indices: new Int32Array(geometry.getIndices() || []),
  9511. };
  9512. };
  9513. return CollisionCoordinatorWorker;
  9514. })();
  9515. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9516. var CollisionCoordinatorLegacy = (function () {
  9517. function CollisionCoordinatorLegacy() {
  9518. this._scaledPosition = BABYLON.Vector3.Zero();
  9519. this._scaledVelocity = BABYLON.Vector3.Zero();
  9520. this._finalPosition = BABYLON.Vector3.Zero();
  9521. }
  9522. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9523. position.divideToRef(collider.radius, this._scaledPosition);
  9524. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9525. collider.collidedMesh = null;
  9526. collider.retry = 0;
  9527. collider.initialVelocity = this._scaledVelocity;
  9528. collider.initialPosition = this._scaledPosition;
  9529. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9530. this._finalPosition.multiplyInPlace(collider.radius);
  9531. //run the callback
  9532. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9533. };
  9534. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9535. this._scene = scene;
  9536. };
  9537. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9538. //Legacy need no destruction method.
  9539. };
  9540. //No update in legacy mode
  9541. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9542. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9543. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9544. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9545. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9546. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9547. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9548. if (excludedMesh === void 0) { excludedMesh = null; }
  9549. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9550. if (collider.retry >= maximumRetry) {
  9551. finalPosition.copyFrom(position);
  9552. return;
  9553. }
  9554. collider._initialize(position, velocity, closeDistance);
  9555. // Check all meshes
  9556. for (var index = 0; index < this._scene.meshes.length; index++) {
  9557. var mesh = this._scene.meshes[index];
  9558. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9559. mesh._checkCollision(collider);
  9560. }
  9561. }
  9562. if (!collider.collisionFound) {
  9563. position.addToRef(velocity, finalPosition);
  9564. return;
  9565. }
  9566. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9567. collider._getResponse(position, velocity);
  9568. }
  9569. if (velocity.length() <= closeDistance) {
  9570. finalPosition.copyFrom(position);
  9571. return;
  9572. }
  9573. collider.retry++;
  9574. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9575. };
  9576. return CollisionCoordinatorLegacy;
  9577. })();
  9578. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9579. })(BABYLON || (BABYLON = {}));
  9580. var BABYLON;
  9581. (function (BABYLON) {
  9582. var VRCameraMetrics = (function () {
  9583. function VRCameraMetrics() {
  9584. this.compensateDistortion = true;
  9585. }
  9586. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9587. get: function () {
  9588. return this.hResolution / (2 * this.vResolution);
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9594. get: function () {
  9595. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9601. get: function () {
  9602. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9603. var h = (4 * meters) / this.hScreenSize;
  9604. return BABYLON.Matrix.Translation(h, 0, 0);
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9610. get: function () {
  9611. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9612. var h = (4 * meters) / this.hScreenSize;
  9613. return BABYLON.Matrix.Translation(-h, 0, 0);
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9619. get: function () {
  9620. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9626. get: function () {
  9627. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. VRCameraMetrics.GetDefault = function () {
  9633. var result = new VRCameraMetrics();
  9634. result.hResolution = 1280;
  9635. result.vResolution = 800;
  9636. result.hScreenSize = 0.149759993;
  9637. result.vScreenSize = 0.0935999975;
  9638. result.vScreenCenter = 0.0467999987,
  9639. result.eyeToScreenDistance = 0.0410000011;
  9640. result.lensSeparationDistance = 0.0635000020;
  9641. result.interpupillaryDistance = 0.0640000030;
  9642. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9643. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9644. result.postProcessScaleFactor = 1.714605507808412;
  9645. result.lensCenterOffset = 0.151976421;
  9646. return result;
  9647. };
  9648. return VRCameraMetrics;
  9649. })();
  9650. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9651. var Camera = (function (_super) {
  9652. __extends(Camera, _super);
  9653. function Camera(name, position, scene) {
  9654. _super.call(this, name, scene);
  9655. this.position = position;
  9656. // Members
  9657. this.upVector = BABYLON.Vector3.Up();
  9658. this.orthoLeft = null;
  9659. this.orthoRight = null;
  9660. this.orthoBottom = null;
  9661. this.orthoTop = null;
  9662. this.fov = 0.8;
  9663. this.minZ = 1.0;
  9664. this.maxZ = 10000.0;
  9665. this.inertia = 0.9;
  9666. this.mode = Camera.PERSPECTIVE_CAMERA;
  9667. this.isIntermediate = false;
  9668. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9669. this.layerMask = 0x0FFFFFFF;
  9670. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9671. // Camera rig members
  9672. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9673. this._rigCameras = new Array();
  9674. // Cache
  9675. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9676. this._projectionMatrix = new BABYLON.Matrix();
  9677. this._postProcesses = new Array();
  9678. this._postProcessesTakenIndices = [];
  9679. this._activeMeshes = new BABYLON.SmartArray(256);
  9680. this._globalPosition = BABYLON.Vector3.Zero();
  9681. scene.addCamera(this);
  9682. if (!scene.activeCamera) {
  9683. scene.activeCamera = this;
  9684. }
  9685. }
  9686. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9687. get: function () {
  9688. return Camera._PERSPECTIVE_CAMERA;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9694. get: function () {
  9695. return Camera._ORTHOGRAPHIC_CAMERA;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9701. get: function () {
  9702. return Camera._FOVMODE_VERTICAL_FIXED;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9708. get: function () {
  9709. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9715. get: function () {
  9716. return Camera._RIG_MODE_NONE;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9722. get: function () {
  9723. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9729. get: function () {
  9730. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9736. get: function () {
  9737. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9743. get: function () {
  9744. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9750. get: function () {
  9751. return Camera._RIG_MODE_VR;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(Camera.prototype, "globalPosition", {
  9757. get: function () {
  9758. return this._globalPosition;
  9759. },
  9760. enumerable: true,
  9761. configurable: true
  9762. });
  9763. Camera.prototype.getActiveMeshes = function () {
  9764. return this._activeMeshes;
  9765. };
  9766. Camera.prototype.isActiveMesh = function (mesh) {
  9767. return (this._activeMeshes.indexOf(mesh) !== -1);
  9768. };
  9769. //Cache
  9770. Camera.prototype._initCache = function () {
  9771. _super.prototype._initCache.call(this);
  9772. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9773. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9774. this._cache.mode = undefined;
  9775. this._cache.minZ = undefined;
  9776. this._cache.maxZ = undefined;
  9777. this._cache.fov = undefined;
  9778. this._cache.aspectRatio = undefined;
  9779. this._cache.orthoLeft = undefined;
  9780. this._cache.orthoRight = undefined;
  9781. this._cache.orthoBottom = undefined;
  9782. this._cache.orthoTop = undefined;
  9783. this._cache.renderWidth = undefined;
  9784. this._cache.renderHeight = undefined;
  9785. };
  9786. Camera.prototype._updateCache = function (ignoreParentClass) {
  9787. if (!ignoreParentClass) {
  9788. _super.prototype._updateCache.call(this);
  9789. }
  9790. var engine = this.getEngine();
  9791. this._cache.position.copyFrom(this.position);
  9792. this._cache.upVector.copyFrom(this.upVector);
  9793. this._cache.mode = this.mode;
  9794. this._cache.minZ = this.minZ;
  9795. this._cache.maxZ = this.maxZ;
  9796. this._cache.fov = this.fov;
  9797. this._cache.aspectRatio = engine.getAspectRatio(this);
  9798. this._cache.orthoLeft = this.orthoLeft;
  9799. this._cache.orthoRight = this.orthoRight;
  9800. this._cache.orthoBottom = this.orthoBottom;
  9801. this._cache.orthoTop = this.orthoTop;
  9802. this._cache.renderWidth = engine.getRenderWidth();
  9803. this._cache.renderHeight = engine.getRenderHeight();
  9804. };
  9805. Camera.prototype._updateFromScene = function () {
  9806. this.updateCache();
  9807. this._update();
  9808. };
  9809. // Synchronized
  9810. Camera.prototype._isSynchronized = function () {
  9811. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9812. };
  9813. Camera.prototype._isSynchronizedViewMatrix = function () {
  9814. if (!_super.prototype._isSynchronized.call(this))
  9815. return false;
  9816. return this._cache.position.equals(this.position)
  9817. && this._cache.upVector.equals(this.upVector)
  9818. && this.isSynchronizedWithParent();
  9819. };
  9820. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9821. var check = this._cache.mode === this.mode
  9822. && this._cache.minZ === this.minZ
  9823. && this._cache.maxZ === this.maxZ;
  9824. if (!check) {
  9825. return false;
  9826. }
  9827. var engine = this.getEngine();
  9828. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9829. check = this._cache.fov === this.fov
  9830. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9831. }
  9832. else {
  9833. check = this._cache.orthoLeft === this.orthoLeft
  9834. && this._cache.orthoRight === this.orthoRight
  9835. && this._cache.orthoBottom === this.orthoBottom
  9836. && this._cache.orthoTop === this.orthoTop
  9837. && this._cache.renderWidth === engine.getRenderWidth()
  9838. && this._cache.renderHeight === engine.getRenderHeight();
  9839. }
  9840. return check;
  9841. };
  9842. // Controls
  9843. Camera.prototype.attachControl = function (element) {
  9844. };
  9845. Camera.prototype.detachControl = function (element) {
  9846. };
  9847. Camera.prototype._update = function () {
  9848. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9849. this._updateRigCameras();
  9850. }
  9851. this._checkInputs();
  9852. };
  9853. Camera.prototype._checkInputs = function () {
  9854. };
  9855. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9856. if (insertAt === void 0) { insertAt = null; }
  9857. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9858. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9859. return 0;
  9860. }
  9861. if (insertAt == null || insertAt < 0) {
  9862. this._postProcesses.push(postProcess);
  9863. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9864. return this._postProcesses.length - 1;
  9865. }
  9866. var add = 0;
  9867. var i;
  9868. var start;
  9869. if (this._postProcesses[insertAt]) {
  9870. start = this._postProcesses.length - 1;
  9871. for (i = start; i >= insertAt + 1; --i) {
  9872. this._postProcesses[i + 1] = this._postProcesses[i];
  9873. }
  9874. add = 1;
  9875. }
  9876. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9877. if (this._postProcessesTakenIndices[i] < insertAt) {
  9878. continue;
  9879. }
  9880. start = this._postProcessesTakenIndices.length - 1;
  9881. for (var j = start; j >= i; --j) {
  9882. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9883. }
  9884. this._postProcessesTakenIndices[i] = insertAt;
  9885. break;
  9886. }
  9887. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9888. this._postProcessesTakenIndices.push(insertAt);
  9889. }
  9890. var result = insertAt + add;
  9891. this._postProcesses[result] = postProcess;
  9892. return result;
  9893. };
  9894. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9895. if (atIndices === void 0) { atIndices = null; }
  9896. var result = [];
  9897. var i;
  9898. var index;
  9899. if (!atIndices) {
  9900. var length = this._postProcesses.length;
  9901. for (i = 0; i < length; i++) {
  9902. if (this._postProcesses[i] !== postProcess) {
  9903. continue;
  9904. }
  9905. delete this._postProcesses[i];
  9906. index = this._postProcessesTakenIndices.indexOf(i);
  9907. this._postProcessesTakenIndices.splice(index, 1);
  9908. }
  9909. }
  9910. else {
  9911. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9912. for (i = 0; i < atIndices.length; i++) {
  9913. var foundPostProcess = this._postProcesses[atIndices[i]];
  9914. if (foundPostProcess !== postProcess) {
  9915. result.push(i);
  9916. continue;
  9917. }
  9918. delete this._postProcesses[atIndices[i]];
  9919. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9920. this._postProcessesTakenIndices.splice(index, 1);
  9921. }
  9922. }
  9923. return result;
  9924. };
  9925. Camera.prototype.getWorldMatrix = function () {
  9926. if (!this._worldMatrix) {
  9927. this._worldMatrix = BABYLON.Matrix.Identity();
  9928. }
  9929. var viewMatrix = this.getViewMatrix();
  9930. viewMatrix.invertToRef(this._worldMatrix);
  9931. return this._worldMatrix;
  9932. };
  9933. Camera.prototype._getViewMatrix = function () {
  9934. return BABYLON.Matrix.Identity();
  9935. };
  9936. Camera.prototype.getViewMatrix = function (force) {
  9937. this._computedViewMatrix = this._computeViewMatrix(force);
  9938. if (!force && this._isSynchronizedViewMatrix()) {
  9939. return this._computedViewMatrix;
  9940. }
  9941. if (!this.parent || !this.parent.getWorldMatrix) {
  9942. this._globalPosition.copyFrom(this.position);
  9943. }
  9944. else {
  9945. if (!this._worldMatrix) {
  9946. this._worldMatrix = BABYLON.Matrix.Identity();
  9947. }
  9948. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9949. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9950. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9951. this._computedViewMatrix.invert();
  9952. this._markSyncedWithParent();
  9953. }
  9954. this._currentRenderId = this.getScene().getRenderId();
  9955. return this._computedViewMatrix;
  9956. };
  9957. Camera.prototype._computeViewMatrix = function (force) {
  9958. if (!force && this._isSynchronizedViewMatrix()) {
  9959. return this._computedViewMatrix;
  9960. }
  9961. this._computedViewMatrix = this._getViewMatrix();
  9962. this._currentRenderId = this.getScene().getRenderId();
  9963. return this._computedViewMatrix;
  9964. };
  9965. Camera.prototype.getProjectionMatrix = function (force) {
  9966. if (!force && this._isSynchronizedProjectionMatrix()) {
  9967. return this._projectionMatrix;
  9968. }
  9969. var engine = this.getEngine();
  9970. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9971. if (this.minZ <= 0) {
  9972. this.minZ = 0.1;
  9973. }
  9974. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9975. return this._projectionMatrix;
  9976. }
  9977. var halfWidth = engine.getRenderWidth() / 2.0;
  9978. var halfHeight = engine.getRenderHeight() / 2.0;
  9979. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9980. return this._projectionMatrix;
  9981. };
  9982. Camera.prototype.dispose = function () {
  9983. // Animations
  9984. this.getScene().stopAnimation(this);
  9985. // Remove from scene
  9986. this.getScene().removeCamera(this);
  9987. while (this._rigCameras.length > 0) {
  9988. this._rigCameras.pop().dispose();
  9989. }
  9990. // Postprocesses
  9991. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9992. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9993. }
  9994. };
  9995. // ---- Camera rigs section ----
  9996. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9997. while (this._rigCameras.length > 0) {
  9998. this._rigCameras.pop().dispose();
  9999. }
  10000. this.cameraRigMode = mode;
  10001. this._cameraRigParams = {};
  10002. switch (this.cameraRigMode) {
  10003. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10004. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10005. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10006. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10007. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10008. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10009. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10010. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10011. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10012. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10013. break;
  10014. }
  10015. var postProcesses = new Array();
  10016. switch (this.cameraRigMode) {
  10017. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10018. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10019. this._rigCameras[0].isIntermediate = true;
  10020. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10021. postProcesses[1].onApply = function (effect) {
  10022. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10023. };
  10024. break;
  10025. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10026. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10027. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10028. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10029. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10030. var secondCamIndex = 1 - firstCamIndex;
  10031. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10032. this._rigCameras[firstCamIndex].isIntermediate = true;
  10033. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10034. break;
  10035. case Camera.RIG_MODE_VR:
  10036. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10037. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10038. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10039. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10040. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10041. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10042. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10043. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10044. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10045. if (metrics.compensateDistortion) {
  10046. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10047. }
  10048. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10049. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10050. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10051. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10052. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10053. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10054. if (metrics.compensateDistortion) {
  10055. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10056. }
  10057. break;
  10058. }
  10059. this._update();
  10060. };
  10061. Camera.prototype._getVRProjectionMatrix = function () {
  10062. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10063. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10064. return this._projectionMatrix;
  10065. };
  10066. Camera.prototype.setCameraRigParameter = function (name, value) {
  10067. this._cameraRigParams[name] = value;
  10068. //provisionnally:
  10069. if (name === "interaxialDistance") {
  10070. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10071. }
  10072. };
  10073. /**
  10074. * May needs to be overridden by children so sub has required properties to be copied
  10075. */
  10076. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10077. return null;
  10078. };
  10079. /**
  10080. * May needs to be overridden by children
  10081. */
  10082. Camera.prototype._updateRigCameras = function () {
  10083. for (var i = 0; i < this._rigCameras.length; i++) {
  10084. this._rigCameras[i].minZ = this.minZ;
  10085. this._rigCameras[i].maxZ = this.maxZ;
  10086. this._rigCameras[i].fov = this.fov;
  10087. }
  10088. // only update viewport when ANAGLYPH
  10089. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10090. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10091. }
  10092. };
  10093. // Statics
  10094. Camera._PERSPECTIVE_CAMERA = 0;
  10095. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10096. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10097. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10098. Camera._RIG_MODE_NONE = 0;
  10099. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10100. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10101. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10102. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10103. Camera._RIG_MODE_VR = 20;
  10104. return Camera;
  10105. })(BABYLON.Node);
  10106. BABYLON.Camera = Camera;
  10107. })(BABYLON || (BABYLON = {}));
  10108. var BABYLON;
  10109. (function (BABYLON) {
  10110. var TargetCamera = (function (_super) {
  10111. __extends(TargetCamera, _super);
  10112. function TargetCamera(name, position, scene) {
  10113. _super.call(this, name, position, scene);
  10114. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10115. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10116. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10117. this.speed = 2.0;
  10118. this.noRotationConstraint = false;
  10119. this.lockedTarget = null;
  10120. this._currentTarget = BABYLON.Vector3.Zero();
  10121. this._viewMatrix = BABYLON.Matrix.Zero();
  10122. this._camMatrix = BABYLON.Matrix.Zero();
  10123. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10124. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10125. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10126. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10127. this._lookAtTemp = BABYLON.Matrix.Zero();
  10128. this._tempMatrix = BABYLON.Matrix.Zero();
  10129. }
  10130. TargetCamera.prototype.getFrontPosition = function (distance) {
  10131. var direction = this.getTarget().subtract(this.position);
  10132. direction.normalize();
  10133. direction.scaleInPlace(distance);
  10134. return this.globalPosition.add(direction);
  10135. };
  10136. TargetCamera.prototype._getLockedTargetPosition = function () {
  10137. if (!this.lockedTarget) {
  10138. return null;
  10139. }
  10140. return this.lockedTarget.position || this.lockedTarget;
  10141. };
  10142. // Cache
  10143. TargetCamera.prototype._initCache = function () {
  10144. _super.prototype._initCache.call(this);
  10145. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10146. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10147. };
  10148. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10149. if (!ignoreParentClass) {
  10150. _super.prototype._updateCache.call(this);
  10151. }
  10152. var lockedTargetPosition = this._getLockedTargetPosition();
  10153. if (!lockedTargetPosition) {
  10154. this._cache.lockedTarget = null;
  10155. }
  10156. else {
  10157. if (!this._cache.lockedTarget) {
  10158. this._cache.lockedTarget = lockedTargetPosition.clone();
  10159. }
  10160. else {
  10161. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10162. }
  10163. }
  10164. this._cache.rotation.copyFrom(this.rotation);
  10165. };
  10166. // Synchronized
  10167. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10168. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10169. return false;
  10170. }
  10171. var lockedTargetPosition = this._getLockedTargetPosition();
  10172. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10173. && this._cache.rotation.equals(this.rotation);
  10174. };
  10175. // Methods
  10176. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10177. var engine = this.getEngine();
  10178. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10179. };
  10180. // Target
  10181. TargetCamera.prototype.setTarget = function (target) {
  10182. this.upVector.normalize();
  10183. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10184. this._camMatrix.invert();
  10185. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10186. var vDir = target.subtract(this.position);
  10187. if (vDir.x >= 0.0) {
  10188. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10189. }
  10190. else {
  10191. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10192. }
  10193. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10194. if (isNaN(this.rotation.x)) {
  10195. this.rotation.x = 0;
  10196. }
  10197. if (isNaN(this.rotation.y)) {
  10198. this.rotation.y = 0;
  10199. }
  10200. if (isNaN(this.rotation.z)) {
  10201. this.rotation.z = 0;
  10202. }
  10203. };
  10204. TargetCamera.prototype.getTarget = function () {
  10205. return this._currentTarget;
  10206. };
  10207. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10208. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10209. };
  10210. TargetCamera.prototype._updatePosition = function () {
  10211. this.position.addInPlace(this.cameraDirection);
  10212. };
  10213. TargetCamera.prototype._checkInputs = function () {
  10214. var needToMove = this._decideIfNeedsToMove();
  10215. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10216. // Move
  10217. if (needToMove) {
  10218. this._updatePosition();
  10219. }
  10220. // Rotate
  10221. if (needToRotate) {
  10222. this.rotation.x += this.cameraRotation.x;
  10223. this.rotation.y += this.cameraRotation.y;
  10224. if (!this.noRotationConstraint) {
  10225. var limit = (Math.PI / 2) * 0.95;
  10226. if (this.rotation.x > limit)
  10227. this.rotation.x = limit;
  10228. if (this.rotation.x < -limit)
  10229. this.rotation.x = -limit;
  10230. }
  10231. }
  10232. // Inertia
  10233. if (needToMove) {
  10234. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10235. this.cameraDirection.x = 0;
  10236. }
  10237. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10238. this.cameraDirection.y = 0;
  10239. }
  10240. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10241. this.cameraDirection.z = 0;
  10242. }
  10243. this.cameraDirection.scaleInPlace(this.inertia);
  10244. }
  10245. if (needToRotate) {
  10246. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10247. this.cameraRotation.x = 0;
  10248. }
  10249. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10250. this.cameraRotation.y = 0;
  10251. }
  10252. this.cameraRotation.scaleInPlace(this.inertia);
  10253. }
  10254. _super.prototype._checkInputs.call(this);
  10255. };
  10256. TargetCamera.prototype._getViewMatrix = function () {
  10257. if (!this.lockedTarget) {
  10258. // Compute
  10259. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10260. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10261. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10262. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10263. this._lookAtTemp.invert();
  10264. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10265. }
  10266. else {
  10267. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10268. }
  10269. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10270. // Computing target and final matrix
  10271. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10272. }
  10273. else {
  10274. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10275. }
  10276. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10277. return this._viewMatrix;
  10278. };
  10279. TargetCamera.prototype._getVRViewMatrix = function () {
  10280. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10282. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10283. // Computing target and final matrix
  10284. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10285. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10286. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10287. return this._viewMatrix;
  10288. };
  10289. /**
  10290. * @override
  10291. * Override Camera.createRigCamera
  10292. */
  10293. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10294. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10295. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10296. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10297. rigCamera._cameraRigParams = {};
  10298. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10299. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10300. }
  10301. return rigCamera;
  10302. }
  10303. return null;
  10304. };
  10305. /**
  10306. * @override
  10307. * Override Camera._updateRigCameras
  10308. */
  10309. TargetCamera.prototype._updateRigCameras = function () {
  10310. switch (this.cameraRigMode) {
  10311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10315. case BABYLON.Camera.RIG_MODE_VR:
  10316. var camLeft = this._rigCameras[0];
  10317. var camRight = this._rigCameras[1];
  10318. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10319. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10320. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10321. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10322. camLeft.position.copyFrom(this.position);
  10323. camRight.position.copyFrom(this.position);
  10324. }
  10325. else {
  10326. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10327. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10328. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10329. camLeft.setTarget(this.getTarget());
  10330. camRight.setTarget(this.getTarget());
  10331. }
  10332. break;
  10333. }
  10334. _super.prototype._updateRigCameras.call(this);
  10335. };
  10336. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10337. if (!this._rigCamTransformMatrix) {
  10338. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10339. }
  10340. var target = this.getTarget();
  10341. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10342. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10344. };
  10345. return TargetCamera;
  10346. })(BABYLON.Camera);
  10347. BABYLON.TargetCamera = TargetCamera;
  10348. })(BABYLON || (BABYLON = {}));
  10349. var BABYLON;
  10350. (function (BABYLON) {
  10351. var FreeCamera = (function (_super) {
  10352. __extends(FreeCamera, _super);
  10353. function FreeCamera(name, position, scene) {
  10354. var _this = this;
  10355. _super.call(this, name, position, scene);
  10356. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10357. this.keysUp = [38];
  10358. this.keysDown = [40];
  10359. this.keysLeft = [37];
  10360. this.keysRight = [39];
  10361. this.checkCollisions = false;
  10362. this.applyGravity = false;
  10363. this.angularSensibility = 2000.0;
  10364. this._keys = [];
  10365. this._collider = new BABYLON.Collider();
  10366. this._needMoveForGravity = false;
  10367. this._oldPosition = BABYLON.Vector3.Zero();
  10368. this._diffPosition = BABYLON.Vector3.Zero();
  10369. this._newPosition = BABYLON.Vector3.Zero();
  10370. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10371. if (collidedMesh === void 0) { collidedMesh = null; }
  10372. //TODO move this to the collision coordinator!
  10373. if (_this.getScene().workerCollisions)
  10374. newPosition.multiplyInPlace(_this._collider.radius);
  10375. var updatePosition = function (newPos) {
  10376. _this._newPosition.copyFrom(newPos);
  10377. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10378. var oldPosition = _this.position.clone();
  10379. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10380. _this.position.addInPlace(_this._diffPosition);
  10381. if (_this.onCollide && collidedMesh) {
  10382. _this.onCollide(collidedMesh);
  10383. }
  10384. }
  10385. };
  10386. updatePosition(newPosition);
  10387. };
  10388. }
  10389. // Controls
  10390. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10391. var _this = this;
  10392. var previousPosition;
  10393. var engine = this.getEngine();
  10394. if (this._attachedElement) {
  10395. return;
  10396. }
  10397. this._attachedElement = element;
  10398. if (this._onMouseDown === undefined) {
  10399. this._onMouseDown = function (evt) {
  10400. previousPosition = {
  10401. x: evt.clientX,
  10402. y: evt.clientY
  10403. };
  10404. if (!noPreventDefault) {
  10405. evt.preventDefault();
  10406. }
  10407. };
  10408. this._onMouseUp = function (evt) {
  10409. previousPosition = null;
  10410. if (!noPreventDefault) {
  10411. evt.preventDefault();
  10412. }
  10413. };
  10414. this._onMouseOut = function (evt) {
  10415. previousPosition = null;
  10416. _this._keys = [];
  10417. if (!noPreventDefault) {
  10418. evt.preventDefault();
  10419. }
  10420. };
  10421. this._onMouseMove = function (evt) {
  10422. if (!previousPosition && !engine.isPointerLock) {
  10423. return;
  10424. }
  10425. var offsetX;
  10426. var offsetY;
  10427. if (!engine.isPointerLock) {
  10428. offsetX = evt.clientX - previousPosition.x;
  10429. offsetY = evt.clientY - previousPosition.y;
  10430. }
  10431. else {
  10432. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10433. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10434. }
  10435. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10436. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10437. previousPosition = {
  10438. x: evt.clientX,
  10439. y: evt.clientY
  10440. };
  10441. if (!noPreventDefault) {
  10442. evt.preventDefault();
  10443. }
  10444. };
  10445. this._onKeyDown = function (evt) {
  10446. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10447. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10448. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10449. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10450. var index = _this._keys.indexOf(evt.keyCode);
  10451. if (index === -1) {
  10452. _this._keys.push(evt.keyCode);
  10453. }
  10454. if (!noPreventDefault) {
  10455. evt.preventDefault();
  10456. }
  10457. }
  10458. };
  10459. this._onKeyUp = function (evt) {
  10460. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10461. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10462. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10463. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10464. var index = _this._keys.indexOf(evt.keyCode);
  10465. if (index >= 0) {
  10466. _this._keys.splice(index, 1);
  10467. }
  10468. if (!noPreventDefault) {
  10469. evt.preventDefault();
  10470. }
  10471. }
  10472. };
  10473. this._onLostFocus = function () {
  10474. _this._keys = [];
  10475. };
  10476. this._reset = function () {
  10477. _this._keys = [];
  10478. previousPosition = null;
  10479. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10480. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10481. };
  10482. }
  10483. element.addEventListener("mousedown", this._onMouseDown, false);
  10484. element.addEventListener("mouseup", this._onMouseUp, false);
  10485. element.addEventListener("mouseout", this._onMouseOut, false);
  10486. element.addEventListener("mousemove", this._onMouseMove, false);
  10487. BABYLON.Tools.RegisterTopRootEvents([
  10488. { name: "keydown", handler: this._onKeyDown },
  10489. { name: "keyup", handler: this._onKeyUp },
  10490. { name: "blur", handler: this._onLostFocus }
  10491. ]);
  10492. };
  10493. FreeCamera.prototype.detachControl = function (element) {
  10494. if (this._attachedElement != element) {
  10495. return;
  10496. }
  10497. element.removeEventListener("mousedown", this._onMouseDown);
  10498. element.removeEventListener("mouseup", this._onMouseUp);
  10499. element.removeEventListener("mouseout", this._onMouseOut);
  10500. element.removeEventListener("mousemove", this._onMouseMove);
  10501. BABYLON.Tools.UnregisterTopRootEvents([
  10502. { name: "keydown", handler: this._onKeyDown },
  10503. { name: "keyup", handler: this._onKeyUp },
  10504. { name: "blur", handler: this._onLostFocus }
  10505. ]);
  10506. this._attachedElement = null;
  10507. if (this._reset) {
  10508. this._reset();
  10509. }
  10510. };
  10511. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10512. var globalPosition;
  10513. if (this.parent) {
  10514. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10515. }
  10516. else {
  10517. globalPosition = this.position;
  10518. }
  10519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10520. this._collider.radius = this.ellipsoid;
  10521. //no need for clone, as long as gravity is not on.
  10522. var actualVelocity = velocity;
  10523. //add gravity to the velocity to prevent the dual-collision checking
  10524. if (this.applyGravity) {
  10525. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10526. actualVelocity = velocity.add(this.getScene().gravity);
  10527. }
  10528. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10529. };
  10530. FreeCamera.prototype._checkInputs = function () {
  10531. if (!this._localDirection) {
  10532. this._localDirection = BABYLON.Vector3.Zero();
  10533. this._transformedDirection = BABYLON.Vector3.Zero();
  10534. }
  10535. // Keyboard
  10536. for (var index = 0; index < this._keys.length; index++) {
  10537. var keyCode = this._keys[index];
  10538. var speed = this._computeLocalCameraSpeed();
  10539. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10540. this._localDirection.copyFromFloats(-speed, 0, 0);
  10541. }
  10542. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10543. this._localDirection.copyFromFloats(0, 0, speed);
  10544. }
  10545. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10546. this._localDirection.copyFromFloats(speed, 0, 0);
  10547. }
  10548. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10549. this._localDirection.copyFromFloats(0, 0, -speed);
  10550. }
  10551. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10552. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10553. this.cameraDirection.addInPlace(this._transformedDirection);
  10554. }
  10555. _super.prototype._checkInputs.call(this);
  10556. };
  10557. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10558. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10559. };
  10560. FreeCamera.prototype._updatePosition = function () {
  10561. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10562. this._collideWithWorld(this.cameraDirection);
  10563. }
  10564. else {
  10565. this.position.addInPlace(this.cameraDirection);
  10566. }
  10567. };
  10568. return FreeCamera;
  10569. })(BABYLON.TargetCamera);
  10570. BABYLON.FreeCamera = FreeCamera;
  10571. })(BABYLON || (BABYLON = {}));
  10572. var BABYLON;
  10573. (function (BABYLON) {
  10574. var FollowCamera = (function (_super) {
  10575. __extends(FollowCamera, _super);
  10576. function FollowCamera(name, position, scene) {
  10577. _super.call(this, name, position, scene);
  10578. this.radius = 12;
  10579. this.rotationOffset = 0;
  10580. this.heightOffset = 4;
  10581. this.cameraAcceleration = 0.05;
  10582. this.maxCameraSpeed = 20;
  10583. }
  10584. FollowCamera.prototype.getRadians = function (degrees) {
  10585. return degrees * Math.PI / 180;
  10586. };
  10587. FollowCamera.prototype.follow = function (cameraTarget) {
  10588. if (!cameraTarget)
  10589. return;
  10590. var yRotation;
  10591. if (cameraTarget.rotationQuaternion) {
  10592. var rotMatrix = new BABYLON.Matrix();
  10593. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10594. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10595. }
  10596. else {
  10597. yRotation = cameraTarget.rotation.y;
  10598. }
  10599. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10600. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10601. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10602. var dx = targetX - this.position.x;
  10603. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10604. var dz = (targetZ) - this.position.z;
  10605. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10606. var vy = dy * this.cameraAcceleration;
  10607. var vz = dz * this.cameraAcceleration * 2;
  10608. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10609. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10610. }
  10611. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10612. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10613. }
  10614. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10615. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10616. }
  10617. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10618. this.setTarget(cameraTarget.position);
  10619. };
  10620. FollowCamera.prototype._checkInputs = function () {
  10621. _super.prototype._checkInputs.call(this);
  10622. this.follow(this.target);
  10623. };
  10624. return FollowCamera;
  10625. })(BABYLON.TargetCamera);
  10626. BABYLON.FollowCamera = FollowCamera;
  10627. var ArcFollowCamera = (function (_super) {
  10628. __extends(ArcFollowCamera, _super);
  10629. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10630. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10631. this.alpha = alpha;
  10632. this.beta = beta;
  10633. this.radius = radius;
  10634. this.target = target;
  10635. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10636. this.follow();
  10637. }
  10638. ArcFollowCamera.prototype.follow = function () {
  10639. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10640. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10641. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10642. this.position = this.target.position.add(this._cartesianCoordinates);
  10643. this.setTarget(this.target.position);
  10644. };
  10645. ArcFollowCamera.prototype._checkInputs = function () {
  10646. _super.prototype._checkInputs.call(this);
  10647. this.follow();
  10648. };
  10649. return ArcFollowCamera;
  10650. })(BABYLON.TargetCamera);
  10651. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10652. })(BABYLON || (BABYLON = {}));
  10653. var BABYLON;
  10654. (function (BABYLON) {
  10655. // We're mainly based on the logic defined into the FreeCamera code
  10656. var TouchCamera = (function (_super) {
  10657. __extends(TouchCamera, _super);
  10658. function TouchCamera(name, position, scene) {
  10659. _super.call(this, name, position, scene);
  10660. this._offsetX = null;
  10661. this._offsetY = null;
  10662. this._pointerCount = 0;
  10663. this._pointerPressed = [];
  10664. this.angularSensibility = 200000.0;
  10665. this.moveSensibility = 500.0;
  10666. }
  10667. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10668. var _this = this;
  10669. var previousPosition;
  10670. if (this._attachedCanvas) {
  10671. return;
  10672. }
  10673. this._attachedCanvas = canvas;
  10674. if (this._onPointerDown === undefined) {
  10675. this._onPointerDown = function (evt) {
  10676. if (!noPreventDefault) {
  10677. evt.preventDefault();
  10678. }
  10679. _this._pointerPressed.push(evt.pointerId);
  10680. if (_this._pointerPressed.length !== 1) {
  10681. return;
  10682. }
  10683. previousPosition = {
  10684. x: evt.clientX,
  10685. y: evt.clientY
  10686. };
  10687. };
  10688. this._onPointerUp = function (evt) {
  10689. if (!noPreventDefault) {
  10690. evt.preventDefault();
  10691. }
  10692. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10693. if (index === -1) {
  10694. return;
  10695. }
  10696. _this._pointerPressed.splice(index, 1);
  10697. if (index != 0) {
  10698. return;
  10699. }
  10700. previousPosition = null;
  10701. _this._offsetX = null;
  10702. _this._offsetY = null;
  10703. };
  10704. this._onPointerMove = function (evt) {
  10705. if (!noPreventDefault) {
  10706. evt.preventDefault();
  10707. }
  10708. if (!previousPosition) {
  10709. return;
  10710. }
  10711. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10712. if (index != 0) {
  10713. return;
  10714. }
  10715. _this._offsetX = evt.clientX - previousPosition.x;
  10716. _this._offsetY = -(evt.clientY - previousPosition.y);
  10717. };
  10718. this._onLostFocus = function () {
  10719. _this._offsetX = null;
  10720. _this._offsetY = null;
  10721. };
  10722. }
  10723. canvas.addEventListener("pointerdown", this._onPointerDown);
  10724. canvas.addEventListener("pointerup", this._onPointerUp);
  10725. canvas.addEventListener("pointerout", this._onPointerUp);
  10726. canvas.addEventListener("pointermove", this._onPointerMove);
  10727. BABYLON.Tools.RegisterTopRootEvents([
  10728. { name: "blur", handler: this._onLostFocus }
  10729. ]);
  10730. };
  10731. TouchCamera.prototype.detachControl = function (canvas) {
  10732. if (this._attachedCanvas != canvas) {
  10733. return;
  10734. }
  10735. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10736. canvas.removeEventListener("pointerup", this._onPointerUp);
  10737. canvas.removeEventListener("pointerout", this._onPointerUp);
  10738. canvas.removeEventListener("pointermove", this._onPointerMove);
  10739. BABYLON.Tools.UnregisterTopRootEvents([
  10740. { name: "blur", handler: this._onLostFocus }
  10741. ]);
  10742. this._attachedCanvas = null;
  10743. };
  10744. TouchCamera.prototype._checkInputs = function () {
  10745. if (this._offsetX) {
  10746. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10747. if (this._pointerPressed.length > 1) {
  10748. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10749. }
  10750. else {
  10751. var speed = this._computeLocalCameraSpeed();
  10752. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10753. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10754. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10755. }
  10756. }
  10757. _super.prototype._checkInputs.call(this);
  10758. };
  10759. return TouchCamera;
  10760. })(BABYLON.FreeCamera);
  10761. BABYLON.TouchCamera = TouchCamera;
  10762. })(BABYLON || (BABYLON = {}));
  10763. var BABYLON;
  10764. (function (BABYLON) {
  10765. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10766. var ArcRotateCamera = (function (_super) {
  10767. __extends(ArcRotateCamera, _super);
  10768. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10769. var _this = this;
  10770. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10771. this.alpha = alpha;
  10772. this.beta = beta;
  10773. this.radius = radius;
  10774. this.target = target;
  10775. this.inertialAlphaOffset = 0;
  10776. this.inertialBetaOffset = 0;
  10777. this.inertialRadiusOffset = 0;
  10778. this.lowerAlphaLimit = null;
  10779. this.upperAlphaLimit = null;
  10780. this.lowerBetaLimit = 0.01;
  10781. this.upperBetaLimit = Math.PI;
  10782. this.lowerRadiusLimit = null;
  10783. this.upperRadiusLimit = null;
  10784. this.angularSensibilityX = 1000.0;
  10785. this.angularSensibilityY = 1000.0;
  10786. this.wheelPrecision = 3.0;
  10787. this.pinchPrecision = 2.0;
  10788. this.panningSensibility = 50.0;
  10789. this.inertialPanningX = 0;
  10790. this.inertialPanningY = 0;
  10791. this.keysUp = [38];
  10792. this.keysDown = [40];
  10793. this.keysLeft = [37];
  10794. this.keysRight = [39];
  10795. this.zoomOnFactor = 1;
  10796. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10797. this.pinchInwards = true;
  10798. this.allowUpsideDown = true;
  10799. this._keys = [];
  10800. this._viewMatrix = new BABYLON.Matrix();
  10801. this._isRightClick = false;
  10802. this._isCtrlPushed = false;
  10803. this.checkCollisions = false;
  10804. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10805. this._collider = new BABYLON.Collider();
  10806. this._previousPosition = BABYLON.Vector3.Zero();
  10807. this._collisionVelocity = BABYLON.Vector3.Zero();
  10808. this._newPosition = BABYLON.Vector3.Zero();
  10809. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10810. if (collidedMesh === void 0) { collidedMesh = null; }
  10811. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10812. newPosition.multiplyInPlace(_this._collider.radius);
  10813. }
  10814. if (!collidedMesh) {
  10815. _this._previousPosition.copyFrom(_this.position);
  10816. }
  10817. else {
  10818. _this.setPosition(_this.position);
  10819. if (_this.onCollide) {
  10820. _this.onCollide(collidedMesh);
  10821. }
  10822. }
  10823. // Recompute because of constraints
  10824. var cosa = Math.cos(_this.alpha);
  10825. var sina = Math.sin(_this.alpha);
  10826. var cosb = Math.cos(_this.beta);
  10827. var sinb = Math.sin(_this.beta);
  10828. var target = _this._getTargetPosition();
  10829. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10830. _this.position.copyFrom(_this._newPosition);
  10831. var up = _this.upVector;
  10832. if (_this.allowUpsideDown && _this.beta < 0) {
  10833. var up = up.clone();
  10834. up = up.negate();
  10835. }
  10836. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10837. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10838. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10839. _this._collisionTriggered = false;
  10840. };
  10841. if (!this.target) {
  10842. this.target = BABYLON.Vector3.Zero();
  10843. }
  10844. this.getViewMatrix();
  10845. }
  10846. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10847. //deprecated angularSensibility support
  10848. get: function () {
  10849. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10850. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10851. },
  10852. //deprecated angularSensibility support
  10853. set: function (value) {
  10854. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10855. this.angularSensibilityX = value;
  10856. this.angularSensibilityY = value;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. ArcRotateCamera.prototype._getTargetPosition = function () {
  10862. return this.target.position || this.target;
  10863. };
  10864. // Cache
  10865. ArcRotateCamera.prototype._initCache = function () {
  10866. _super.prototype._initCache.call(this);
  10867. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10868. this._cache.alpha = undefined;
  10869. this._cache.beta = undefined;
  10870. this._cache.radius = undefined;
  10871. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10872. };
  10873. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10874. if (!ignoreParentClass) {
  10875. _super.prototype._updateCache.call(this);
  10876. }
  10877. this._cache.target.copyFrom(this._getTargetPosition());
  10878. this._cache.alpha = this.alpha;
  10879. this._cache.beta = this.beta;
  10880. this._cache.radius = this.radius;
  10881. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10882. };
  10883. // Synchronized
  10884. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10885. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10886. return false;
  10887. return this._cache.target.equals(this._getTargetPosition())
  10888. && this._cache.alpha === this.alpha
  10889. && this._cache.beta === this.beta
  10890. && this._cache.radius === this.radius
  10891. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10892. };
  10893. // Methods
  10894. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10895. var _this = this;
  10896. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10897. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10898. var previousPinchDistance = 0;
  10899. var pointers = new BABYLON.SmartCollection();
  10900. if (this._attachedElement) {
  10901. return;
  10902. }
  10903. this._attachedElement = element;
  10904. var engine = this.getEngine();
  10905. if (this._onPointerDown === undefined) {
  10906. this._onPointerDown = function (evt) {
  10907. // Manage panning with right click
  10908. _this._isRightClick = evt.button === 2 ? true : false;
  10909. // manage pointers
  10910. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10911. cacheSoloPointer = pointers.item(evt.pointerId);
  10912. if (!noPreventDefault) {
  10913. evt.preventDefault();
  10914. }
  10915. };
  10916. this._onPointerUp = function (evt) {
  10917. cacheSoloPointer = null;
  10918. previousPinchDistance = 0;
  10919. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10920. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10921. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10922. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10923. pointers.empty();
  10924. if (!noPreventDefault) {
  10925. evt.preventDefault();
  10926. }
  10927. };
  10928. this._onContextMenu = function (evt) {
  10929. evt.preventDefault();
  10930. };
  10931. this._onPointerMove = function (evt) {
  10932. if (!noPreventDefault) {
  10933. evt.preventDefault();
  10934. }
  10935. switch (pointers.count) {
  10936. case 1:
  10937. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10938. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10939. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10940. }
  10941. else {
  10942. var offsetX = evt.clientX - cacheSoloPointer.x;
  10943. var offsetY = evt.clientY - cacheSoloPointer.y;
  10944. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10945. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10946. }
  10947. cacheSoloPointer.x = evt.clientX;
  10948. cacheSoloPointer.y = evt.clientY;
  10949. break;
  10950. case 2:
  10951. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10952. pointers.item(evt.pointerId).x = evt.clientX;
  10953. pointers.item(evt.pointerId).y = evt.clientY;
  10954. var direction = _this.pinchInwards ? 1 : -1;
  10955. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10956. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10957. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10958. if (previousPinchDistance === 0) {
  10959. previousPinchDistance = pinchSquaredDistance;
  10960. return;
  10961. }
  10962. if (pinchSquaredDistance !== previousPinchDistance) {
  10963. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10964. previousPinchDistance = pinchSquaredDistance;
  10965. }
  10966. break;
  10967. default:
  10968. if (pointers.item(evt.pointerId)) {
  10969. pointers.item(evt.pointerId).x = evt.clientX;
  10970. pointers.item(evt.pointerId).y = evt.clientY;
  10971. }
  10972. }
  10973. };
  10974. this._onMouseMove = function (evt) {
  10975. if (!engine.isPointerLock) {
  10976. return;
  10977. }
  10978. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10979. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10980. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10981. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10982. if (!noPreventDefault) {
  10983. evt.preventDefault();
  10984. }
  10985. };
  10986. this._wheel = function (event) {
  10987. var delta = 0;
  10988. if (event.wheelDelta) {
  10989. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10990. }
  10991. else if (event.detail) {
  10992. delta = -event.detail / _this.wheelPrecision;
  10993. }
  10994. if (delta)
  10995. _this.inertialRadiusOffset += delta;
  10996. if (event.preventDefault) {
  10997. if (!noPreventDefault) {
  10998. event.preventDefault();
  10999. }
  11000. }
  11001. };
  11002. this._onKeyDown = function (evt) {
  11003. _this._isCtrlPushed = evt.ctrlKey;
  11004. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11005. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11006. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11007. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11008. var index = _this._keys.indexOf(evt.keyCode);
  11009. if (index === -1) {
  11010. _this._keys.push(evt.keyCode);
  11011. }
  11012. if (evt.preventDefault) {
  11013. if (!noPreventDefault) {
  11014. evt.preventDefault();
  11015. }
  11016. }
  11017. }
  11018. };
  11019. this._onKeyUp = function (evt) {
  11020. _this._isCtrlPushed = evt.ctrlKey;
  11021. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11022. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11023. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11024. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11025. var index = _this._keys.indexOf(evt.keyCode);
  11026. if (index >= 0) {
  11027. _this._keys.splice(index, 1);
  11028. }
  11029. if (evt.preventDefault) {
  11030. if (!noPreventDefault) {
  11031. evt.preventDefault();
  11032. }
  11033. }
  11034. }
  11035. };
  11036. this._onLostFocus = function () {
  11037. _this._keys = [];
  11038. pointers.empty();
  11039. previousPinchDistance = 0;
  11040. cacheSoloPointer = null;
  11041. };
  11042. this._onGestureStart = function (e) {
  11043. if (window.MSGesture === undefined) {
  11044. return;
  11045. }
  11046. if (!_this._MSGestureHandler) {
  11047. _this._MSGestureHandler = new MSGesture();
  11048. _this._MSGestureHandler.target = element;
  11049. }
  11050. _this._MSGestureHandler.addPointer(e.pointerId);
  11051. };
  11052. this._onGesture = function (e) {
  11053. _this.radius *= e.scale;
  11054. if (e.preventDefault) {
  11055. if (!noPreventDefault) {
  11056. e.stopPropagation();
  11057. e.preventDefault();
  11058. }
  11059. }
  11060. };
  11061. this._reset = function () {
  11062. _this._keys = [];
  11063. _this.inertialAlphaOffset = 0;
  11064. _this.inertialBetaOffset = 0;
  11065. _this.inertialRadiusOffset = 0;
  11066. pointers.empty();
  11067. previousPinchDistance = 0;
  11068. cacheSoloPointer = null;
  11069. };
  11070. }
  11071. if (!useCtrlForPanning) {
  11072. element.addEventListener("contextmenu", this._onContextMenu, false);
  11073. }
  11074. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11075. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11076. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11077. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11078. element.addEventListener("mousemove", this._onMouseMove, false);
  11079. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11080. element.addEventListener("MSGestureChange", this._onGesture, false);
  11081. element.addEventListener('mousewheel', this._wheel, false);
  11082. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11083. BABYLON.Tools.RegisterTopRootEvents([
  11084. { name: "keydown", handler: this._onKeyDown },
  11085. { name: "keyup", handler: this._onKeyUp },
  11086. { name: "blur", handler: this._onLostFocus }
  11087. ]);
  11088. };
  11089. ArcRotateCamera.prototype.detachControl = function (element) {
  11090. if (this._attachedElement !== element) {
  11091. return;
  11092. }
  11093. element.removeEventListener("contextmenu", this._onContextMenu);
  11094. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11095. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11096. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11097. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11098. element.removeEventListener("mousemove", this._onMouseMove);
  11099. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11100. element.removeEventListener("MSGestureChange", this._onGesture);
  11101. element.removeEventListener('mousewheel', this._wheel);
  11102. element.removeEventListener('DOMMouseScroll', this._wheel);
  11103. BABYLON.Tools.UnregisterTopRootEvents([
  11104. { name: "keydown", handler: this._onKeyDown },
  11105. { name: "keyup", handler: this._onKeyUp },
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. this._MSGestureHandler = null;
  11109. this._attachedElement = null;
  11110. if (this._reset) {
  11111. this._reset();
  11112. }
  11113. };
  11114. ArcRotateCamera.prototype._checkInputs = function () {
  11115. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11116. if (this._collisionTriggered) {
  11117. return;
  11118. }
  11119. // Keyboard
  11120. for (var index = 0; index < this._keys.length; index++) {
  11121. var keyCode = this._keys[index];
  11122. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11123. this.inertialAlphaOffset -= 0.01;
  11124. }
  11125. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11126. this.inertialBetaOffset -= 0.01;
  11127. }
  11128. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11129. this.inertialAlphaOffset += 0.01;
  11130. }
  11131. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11132. this.inertialBetaOffset += 0.01;
  11133. }
  11134. }
  11135. // Inertia
  11136. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11137. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11138. this.beta += this.inertialBetaOffset;
  11139. this.radius -= this.inertialRadiusOffset;
  11140. this.inertialAlphaOffset *= this.inertia;
  11141. this.inertialBetaOffset *= this.inertia;
  11142. this.inertialRadiusOffset *= this.inertia;
  11143. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11144. this.inertialAlphaOffset = 0;
  11145. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11146. this.inertialBetaOffset = 0;
  11147. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11148. this.inertialRadiusOffset = 0;
  11149. }
  11150. // Panning inertia
  11151. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11152. if (!this._localDirection) {
  11153. this._localDirection = BABYLON.Vector3.Zero();
  11154. this._transformedDirection = BABYLON.Vector3.Zero();
  11155. }
  11156. this.inertialPanningX *= this.inertia;
  11157. this.inertialPanningY *= this.inertia;
  11158. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11159. this.inertialPanningX = 0;
  11160. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11161. this.inertialPanningY = 0;
  11162. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11163. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11164. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11165. this.target.addInPlace(this._transformedDirection);
  11166. }
  11167. // Limits
  11168. this._checkLimits();
  11169. _super.prototype._checkInputs.call(this);
  11170. };
  11171. ArcRotateCamera.prototype._checkLimits = function () {
  11172. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11173. if (this.allowUpsideDown && this.beta > Math.PI) {
  11174. this.beta = this.beta - (2 * Math.PI);
  11175. }
  11176. }
  11177. else {
  11178. if (this.beta < this.lowerBetaLimit) {
  11179. this.beta = this.lowerBetaLimit;
  11180. }
  11181. }
  11182. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11183. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11184. this.beta = this.beta + (2 * Math.PI);
  11185. }
  11186. }
  11187. else {
  11188. if (this.beta > this.upperBetaLimit) {
  11189. this.beta = this.upperBetaLimit;
  11190. }
  11191. }
  11192. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11193. this.alpha = this.lowerAlphaLimit;
  11194. }
  11195. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11196. this.alpha = this.upperAlphaLimit;
  11197. }
  11198. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11199. this.radius = this.lowerRadiusLimit;
  11200. }
  11201. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11202. this.radius = this.upperRadiusLimit;
  11203. }
  11204. };
  11205. ArcRotateCamera.prototype.setPosition = function (position) {
  11206. if (this.position.equals(position)) {
  11207. return;
  11208. }
  11209. var radiusv3 = position.subtract(this._getTargetPosition());
  11210. this.radius = radiusv3.length();
  11211. // Alpha
  11212. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11213. if (radiusv3.z < 0) {
  11214. this.alpha = 2 * Math.PI - this.alpha;
  11215. }
  11216. // Beta
  11217. this.beta = Math.acos(radiusv3.y / this.radius);
  11218. this._checkLimits();
  11219. };
  11220. ArcRotateCamera.prototype.setTarget = function (target) {
  11221. this.target = target;
  11222. };
  11223. ArcRotateCamera.prototype._getViewMatrix = function () {
  11224. // Compute
  11225. var cosa = Math.cos(this.alpha);
  11226. var sina = Math.sin(this.alpha);
  11227. var cosb = Math.cos(this.beta);
  11228. var sinb = Math.sin(this.beta);
  11229. var target = this._getTargetPosition();
  11230. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11231. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11232. this._collider.radius = this.collisionRadius;
  11233. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11234. this._collisionTriggered = true;
  11235. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11236. }
  11237. else {
  11238. this.position.copyFrom(this._newPosition);
  11239. var up = this.upVector;
  11240. if (this.allowUpsideDown && this.beta < 0) {
  11241. var up = up.clone();
  11242. up = up.negate();
  11243. }
  11244. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11245. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11246. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11247. }
  11248. return this._viewMatrix;
  11249. };
  11250. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11251. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11252. meshes = meshes || this.getScene().meshes;
  11253. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11254. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11255. this.radius = distance * this.zoomOnFactor;
  11256. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11257. };
  11258. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11259. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11260. var meshesOrMinMaxVector;
  11261. var distance;
  11262. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11263. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11264. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11265. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11266. }
  11267. else {
  11268. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11269. distance = meshesOrMinMaxVectorAndDistance.distance;
  11270. }
  11271. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11272. if (!doNotUpdateMaxZ) {
  11273. this.maxZ = distance * 2;
  11274. }
  11275. };
  11276. /**
  11277. * @override
  11278. * Override Camera.createRigCamera
  11279. */
  11280. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11281. switch (this.cameraRigMode) {
  11282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11286. case BABYLON.Camera.RIG_MODE_VR:
  11287. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11288. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11289. }
  11290. };
  11291. /**
  11292. * @override
  11293. * Override Camera._updateRigCameras
  11294. */
  11295. ArcRotateCamera.prototype._updateRigCameras = function () {
  11296. switch (this.cameraRigMode) {
  11297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11298. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11299. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11300. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11301. case BABYLON.Camera.RIG_MODE_VR:
  11302. var camLeft = this._rigCameras[0];
  11303. var camRight = this._rigCameras[1];
  11304. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11305. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11306. camLeft.beta = camRight.beta = this.beta;
  11307. camLeft.radius = camRight.radius = this.radius;
  11308. break;
  11309. }
  11310. _super.prototype._updateRigCameras.call(this);
  11311. };
  11312. return ArcRotateCamera;
  11313. })(BABYLON.TargetCamera);
  11314. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11315. })(BABYLON || (BABYLON = {}));
  11316. var BABYLON;
  11317. (function (BABYLON) {
  11318. var RenderingManager = (function () {
  11319. function RenderingManager(scene) {
  11320. this._renderingGroups = new Array();
  11321. this._scene = scene;
  11322. }
  11323. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11324. if (this._scene._activeParticleSystems.length === 0) {
  11325. return;
  11326. }
  11327. // Particles
  11328. var activeCamera = this._scene.activeCamera;
  11329. var beforeParticlesDate = BABYLON.Tools.Now;
  11330. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11331. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11332. if (particleSystem.renderingGroupId !== index) {
  11333. continue;
  11334. }
  11335. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11336. continue;
  11337. }
  11338. this._clearDepthBuffer();
  11339. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11340. this._scene._activeParticles += particleSystem.render();
  11341. }
  11342. }
  11343. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11344. };
  11345. RenderingManager.prototype._renderSprites = function (index) {
  11346. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11347. return;
  11348. }
  11349. // Sprites
  11350. var activeCamera = this._scene.activeCamera;
  11351. var beforeSpritessDate = BABYLON.Tools.Now;
  11352. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11353. var spriteManager = this._scene.spriteManagers[id];
  11354. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11355. this._clearDepthBuffer();
  11356. spriteManager.render();
  11357. }
  11358. }
  11359. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11360. };
  11361. RenderingManager.prototype._clearDepthBuffer = function () {
  11362. if (this._depthBufferAlreadyCleaned) {
  11363. return;
  11364. }
  11365. this._scene.getEngine().clear(0, false, true);
  11366. this._depthBufferAlreadyCleaned = true;
  11367. };
  11368. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11369. if (this._currentRenderSprites) {
  11370. this._renderSprites(this._currentIndex);
  11371. }
  11372. if (this._currentRenderParticles) {
  11373. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11374. }
  11375. };
  11376. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11377. this._currentActiveMeshes = activeMeshes;
  11378. this._currentRenderParticles = renderParticles;
  11379. this._currentRenderSprites = renderSprites;
  11380. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11381. this._depthBufferAlreadyCleaned = false;
  11382. var renderingGroup = this._renderingGroups[index];
  11383. var needToStepBack = false;
  11384. this._currentIndex = index;
  11385. if (renderingGroup) {
  11386. this._clearDepthBuffer();
  11387. if (!renderingGroup.onBeforeTransparentRendering) {
  11388. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11389. }
  11390. if (!renderingGroup.render(customRenderFunction)) {
  11391. this._renderingGroups.splice(index, 1);
  11392. needToStepBack = true;
  11393. this._renderSpritesAndParticles();
  11394. }
  11395. }
  11396. else {
  11397. this._renderSpritesAndParticles();
  11398. }
  11399. if (needToStepBack) {
  11400. index--;
  11401. }
  11402. }
  11403. };
  11404. RenderingManager.prototype.reset = function () {
  11405. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11406. if (renderingGroup) {
  11407. renderingGroup.prepare();
  11408. }
  11409. });
  11410. };
  11411. RenderingManager.prototype.dispatch = function (subMesh) {
  11412. var mesh = subMesh.getMesh();
  11413. var renderingGroupId = mesh.renderingGroupId || 0;
  11414. if (!this._renderingGroups[renderingGroupId]) {
  11415. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11416. }
  11417. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11418. };
  11419. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11420. return RenderingManager;
  11421. })();
  11422. BABYLON.RenderingManager = RenderingManager;
  11423. })(BABYLON || (BABYLON = {}));
  11424. var BABYLON;
  11425. (function (BABYLON) {
  11426. var RenderingGroup = (function () {
  11427. function RenderingGroup(index, scene) {
  11428. this.index = index;
  11429. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11430. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11431. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11432. this._scene = scene;
  11433. }
  11434. RenderingGroup.prototype.render = function (customRenderFunction) {
  11435. if (customRenderFunction) {
  11436. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11437. return true;
  11438. }
  11439. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11440. if (this.onBeforeTransparentRendering) {
  11441. this.onBeforeTransparentRendering();
  11442. }
  11443. return false;
  11444. }
  11445. var engine = this._scene.getEngine();
  11446. // Opaque
  11447. var subIndex;
  11448. var submesh;
  11449. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11450. submesh = this._opaqueSubMeshes.data[subIndex];
  11451. submesh.render(false);
  11452. }
  11453. // Alpha test
  11454. engine.setAlphaTesting(true);
  11455. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11456. submesh = this._alphaTestSubMeshes.data[subIndex];
  11457. submesh.render(false);
  11458. }
  11459. engine.setAlphaTesting(false);
  11460. if (this.onBeforeTransparentRendering) {
  11461. this.onBeforeTransparentRendering();
  11462. }
  11463. // Transparent
  11464. if (this._transparentSubMeshes.length) {
  11465. // Sorting
  11466. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11467. submesh = this._transparentSubMeshes.data[subIndex];
  11468. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11469. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11470. }
  11471. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11472. sortedArray.sort(function (a, b) {
  11473. // Alpha index first
  11474. if (a._alphaIndex > b._alphaIndex) {
  11475. return 1;
  11476. }
  11477. if (a._alphaIndex < b._alphaIndex) {
  11478. return -1;
  11479. }
  11480. // Then distance to camera
  11481. if (a._distanceToCamera < b._distanceToCamera) {
  11482. return 1;
  11483. }
  11484. if (a._distanceToCamera > b._distanceToCamera) {
  11485. return -1;
  11486. }
  11487. return 0;
  11488. });
  11489. // Rendering
  11490. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11491. submesh = sortedArray[subIndex];
  11492. submesh.render(true);
  11493. }
  11494. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11495. }
  11496. return true;
  11497. };
  11498. RenderingGroup.prototype.prepare = function () {
  11499. this._opaqueSubMeshes.reset();
  11500. this._transparentSubMeshes.reset();
  11501. this._alphaTestSubMeshes.reset();
  11502. };
  11503. RenderingGroup.prototype.dispatch = function (subMesh) {
  11504. var material = subMesh.getMaterial();
  11505. var mesh = subMesh.getMesh();
  11506. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11507. this._transparentSubMeshes.push(subMesh);
  11508. }
  11509. else if (material.needAlphaTesting()) {
  11510. this._alphaTestSubMeshes.push(subMesh);
  11511. }
  11512. else {
  11513. this._opaqueSubMeshes.push(subMesh); // Opaque
  11514. }
  11515. };
  11516. return RenderingGroup;
  11517. })();
  11518. BABYLON.RenderingGroup = RenderingGroup;
  11519. })(BABYLON || (BABYLON = {}));
  11520. var BABYLON;
  11521. (function (BABYLON) {
  11522. /**
  11523. * Represents a scene to be rendered by the engine.
  11524. * @see http://doc.babylonjs.com/page.php?p=21911
  11525. */
  11526. var Scene = (function () {
  11527. /**
  11528. * @constructor
  11529. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11530. */
  11531. function Scene(engine) {
  11532. // Members
  11533. this.autoClear = true;
  11534. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11535. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11536. this.forceWireframe = false;
  11537. this.forcePointsCloud = false;
  11538. this.forceShowBoundingBoxes = false;
  11539. this.animationsEnabled = true;
  11540. this.constantlyUpdateMeshUnderPointer = false;
  11541. 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
  11542. // Fog
  11543. /**
  11544. * is fog enabled on this scene.
  11545. * @type {boolean}
  11546. */
  11547. this.fogEnabled = true;
  11548. this.fogMode = Scene.FOGMODE_NONE;
  11549. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11550. this.fogDensity = 0.1;
  11551. this.fogStart = 0;
  11552. this.fogEnd = 1000.0;
  11553. // Lights
  11554. /**
  11555. * is shadow enabled on this scene.
  11556. * @type {boolean}
  11557. */
  11558. this.shadowsEnabled = true;
  11559. /**
  11560. * is light enabled on this scene.
  11561. * @type {boolean}
  11562. */
  11563. this.lightsEnabled = true;
  11564. /**
  11565. * All of the lights added to this scene.
  11566. * @see BABYLON.Light
  11567. * @type {BABYLON.Light[]}
  11568. */
  11569. this.lights = new Array();
  11570. // Cameras
  11571. /**
  11572. * All of the cameras added to this scene.
  11573. * @see BABYLON.Camera
  11574. * @type {BABYLON.Camera[]}
  11575. */
  11576. this.cameras = new Array();
  11577. this.activeCameras = new Array();
  11578. // Meshes
  11579. /**
  11580. * All of the (abstract) meshes added to this scene.
  11581. * @see BABYLON.AbstractMesh
  11582. * @type {BABYLON.AbstractMesh[]}
  11583. */
  11584. this.meshes = new Array();
  11585. // Geometries
  11586. this._geometries = new Array();
  11587. this.materials = new Array();
  11588. this.multiMaterials = new Array();
  11589. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11590. // Textures
  11591. this.texturesEnabled = true;
  11592. this.textures = new Array();
  11593. // Particles
  11594. this.particlesEnabled = true;
  11595. this.particleSystems = new Array();
  11596. // Sprites
  11597. this.spritesEnabled = true;
  11598. this.spriteManagers = new Array();
  11599. // Layers
  11600. this.layers = new Array();
  11601. // Skeletons
  11602. this.skeletonsEnabled = true;
  11603. this.skeletons = new Array();
  11604. // Lens flares
  11605. this.lensFlaresEnabled = true;
  11606. this.lensFlareSystems = new Array();
  11607. // Collisions
  11608. this.collisionsEnabled = true;
  11609. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11610. // Postprocesses
  11611. this.postProcessesEnabled = true;
  11612. // Customs render targets
  11613. this.renderTargetsEnabled = true;
  11614. this.dumpNextRenderTargets = false;
  11615. this.customRenderTargets = new Array();
  11616. // Imported meshes
  11617. this.importedMeshesFiles = new Array();
  11618. // Probes
  11619. this.probesEnabled = true;
  11620. this.reflectionProbes = new Array();
  11621. this._actionManagers = new Array();
  11622. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11623. // Procedural textures
  11624. this.proceduralTexturesEnabled = true;
  11625. this._proceduralTextures = new Array();
  11626. this.soundTracks = new Array();
  11627. this._audioEnabled = true;
  11628. this._headphone = false;
  11629. this._totalVertices = 0;
  11630. this._activeIndices = 0;
  11631. this._activeParticles = 0;
  11632. this._lastFrameDuration = 0;
  11633. this._evaluateActiveMeshesDuration = 0;
  11634. this._renderTargetsDuration = 0;
  11635. this._particlesDuration = 0;
  11636. this._renderDuration = 0;
  11637. this._spritesDuration = 0;
  11638. this._animationRatio = 0;
  11639. this._renderId = 0;
  11640. this._executeWhenReadyTimeoutId = -1;
  11641. this._toBeDisposed = new BABYLON.SmartArray(256);
  11642. this._onReadyCallbacks = new Array();
  11643. this._pendingData = []; //ANY
  11644. this._onBeforeRenderCallbacks = new Array();
  11645. this._onAfterRenderCallbacks = new Array();
  11646. this._activeMeshes = new BABYLON.SmartArray(256);
  11647. this._processedMaterials = new BABYLON.SmartArray(256);
  11648. this._renderTargets = new BABYLON.SmartArray(256);
  11649. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11650. this._activeSkeletons = new BABYLON.SmartArray(32);
  11651. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11652. this._activeBones = 0;
  11653. this._activeAnimatables = new Array();
  11654. this._transformMatrix = BABYLON.Matrix.Zero();
  11655. this._edgesRenderers = new BABYLON.SmartArray(16);
  11656. this._uniqueIdCounter = 0;
  11657. this._engine = engine;
  11658. engine.scenes.push(this);
  11659. this._renderingManager = new BABYLON.RenderingManager(this);
  11660. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11661. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11662. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11663. if (BABYLON.OutlineRenderer) {
  11664. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11665. }
  11666. this.attachControl();
  11667. this._debugLayer = new BABYLON.DebugLayer(this);
  11668. if (BABYLON.SoundTrack) {
  11669. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11670. }
  11671. //simplification queue
  11672. if (BABYLON.SimplificationQueue) {
  11673. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11674. }
  11675. //collision coordinator initialization. For now legacy per default.
  11676. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11677. }
  11678. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11679. get: function () {
  11680. return Scene._FOGMODE_NONE;
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11686. get: function () {
  11687. return Scene._FOGMODE_EXP;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11693. get: function () {
  11694. return Scene._FOGMODE_EXP2;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11700. get: function () {
  11701. return Scene._FOGMODE_LINEAR;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Scene.prototype, "debugLayer", {
  11707. // Properties
  11708. get: function () {
  11709. return this._debugLayer;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11715. get: function () {
  11716. return this._workerCollisions;
  11717. },
  11718. set: function (enabled) {
  11719. enabled = (enabled && !!Worker);
  11720. this._workerCollisions = enabled;
  11721. if (this.collisionCoordinator) {
  11722. this.collisionCoordinator.destroy();
  11723. }
  11724. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11725. this.collisionCoordinator.init(this);
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11731. get: function () {
  11732. return this._selectionOctree;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11738. /**
  11739. * The mesh that is currently under the pointer.
  11740. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11741. */
  11742. get: function () {
  11743. return this._meshUnderPointer;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Scene.prototype, "pointerX", {
  11749. /**
  11750. * Current on-screen X position of the pointer
  11751. * @return {number} X position of the pointer
  11752. */
  11753. get: function () {
  11754. return this._pointerX;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Scene.prototype, "pointerY", {
  11760. /**
  11761. * Current on-screen Y position of the pointer
  11762. * @return {number} Y position of the pointer
  11763. */
  11764. get: function () {
  11765. return this._pointerY;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Scene.prototype.getCachedMaterial = function () {
  11771. return this._cachedMaterial;
  11772. };
  11773. Scene.prototype.getBoundingBoxRenderer = function () {
  11774. return this._boundingBoxRenderer;
  11775. };
  11776. Scene.prototype.getOutlineRenderer = function () {
  11777. return this._outlineRenderer;
  11778. };
  11779. Scene.prototype.getEngine = function () {
  11780. return this._engine;
  11781. };
  11782. Scene.prototype.getTotalVertices = function () {
  11783. return this._totalVertices;
  11784. };
  11785. Scene.prototype.getActiveIndices = function () {
  11786. return this._activeIndices;
  11787. };
  11788. Scene.prototype.getActiveParticles = function () {
  11789. return this._activeParticles;
  11790. };
  11791. Scene.prototype.getActiveBones = function () {
  11792. return this._activeBones;
  11793. };
  11794. // Stats
  11795. Scene.prototype.getLastFrameDuration = function () {
  11796. return this._lastFrameDuration;
  11797. };
  11798. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11799. return this._evaluateActiveMeshesDuration;
  11800. };
  11801. Scene.prototype.getActiveMeshes = function () {
  11802. return this._activeMeshes;
  11803. };
  11804. Scene.prototype.getRenderTargetsDuration = function () {
  11805. return this._renderTargetsDuration;
  11806. };
  11807. Scene.prototype.getRenderDuration = function () {
  11808. return this._renderDuration;
  11809. };
  11810. Scene.prototype.getParticlesDuration = function () {
  11811. return this._particlesDuration;
  11812. };
  11813. Scene.prototype.getSpritesDuration = function () {
  11814. return this._spritesDuration;
  11815. };
  11816. Scene.prototype.getAnimationRatio = function () {
  11817. return this._animationRatio;
  11818. };
  11819. Scene.prototype.getRenderId = function () {
  11820. return this._renderId;
  11821. };
  11822. Scene.prototype.incrementRenderId = function () {
  11823. this._renderId++;
  11824. };
  11825. Scene.prototype._updatePointerPosition = function (evt) {
  11826. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11827. this._pointerX = evt.clientX - canvasRect.left;
  11828. this._pointerY = evt.clientY - canvasRect.top;
  11829. if (this.cameraToUseForPointers) {
  11830. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11831. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11832. }
  11833. };
  11834. // Pointers handling
  11835. Scene.prototype.attachControl = function () {
  11836. var _this = this;
  11837. var spritePredicate = function (sprite) {
  11838. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11839. };
  11840. this._onPointerMove = function (evt) {
  11841. var canvas = _this._engine.getRenderingCanvas();
  11842. _this._updatePointerPosition(evt);
  11843. // Meshes
  11844. 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);
  11845. if (pickResult.hit && pickResult.pickedMesh) {
  11846. _this._meshUnderPointer = pickResult.pickedMesh;
  11847. _this.setPointerOverMesh(pickResult.pickedMesh);
  11848. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11849. canvas.style.cursor = "pointer";
  11850. }
  11851. else {
  11852. canvas.style.cursor = "";
  11853. }
  11854. }
  11855. else {
  11856. // Sprites
  11857. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11858. if (pickResult.hit && pickResult.pickedSprite) {
  11859. canvas.style.cursor = "pointer";
  11860. }
  11861. else {
  11862. // Restore pointer
  11863. _this.setPointerOverMesh(null);
  11864. canvas.style.cursor = "";
  11865. _this._meshUnderPointer = null;
  11866. }
  11867. }
  11868. if (_this.onPointerMove) {
  11869. _this.onPointerMove(evt, pickResult);
  11870. }
  11871. };
  11872. this._onPointerDown = function (evt) {
  11873. _this._updatePointerPosition(evt);
  11874. var predicate = null;
  11875. // Meshes
  11876. if (!_this.onPointerDown) {
  11877. predicate = function (mesh) {
  11878. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11879. };
  11880. }
  11881. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11882. if (pickResult.hit && pickResult.pickedMesh) {
  11883. if (pickResult.pickedMesh.actionManager) {
  11884. switch (evt.button) {
  11885. case 0:
  11886. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11887. break;
  11888. case 1:
  11889. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11890. break;
  11891. case 2:
  11892. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11893. break;
  11894. }
  11895. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11896. }
  11897. }
  11898. if (_this.onPointerDown) {
  11899. _this.onPointerDown(evt, pickResult);
  11900. }
  11901. // Sprites
  11902. if (_this.spriteManagers.length > 0) {
  11903. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11904. if (pickResult.hit && pickResult.pickedSprite) {
  11905. if (pickResult.pickedSprite.actionManager) {
  11906. switch (evt.button) {
  11907. case 0:
  11908. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11909. break;
  11910. case 1:
  11911. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11912. break;
  11913. case 2:
  11914. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11915. break;
  11916. }
  11917. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11918. }
  11919. }
  11920. }
  11921. };
  11922. this._onPointerUp = function (evt) {
  11923. var predicate = null;
  11924. _this._updatePointerPosition(evt);
  11925. if (!_this.onPointerUp) {
  11926. predicate = function (mesh) {
  11927. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11928. };
  11929. }
  11930. // Meshes
  11931. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11932. if (pickResult.hit && pickResult.pickedMesh) {
  11933. if (pickResult.pickedMesh.actionManager) {
  11934. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11935. }
  11936. }
  11937. if (_this.onPointerUp) {
  11938. _this.onPointerUp(evt, pickResult);
  11939. }
  11940. // Sprites
  11941. if (_this.spriteManagers.length > 0) {
  11942. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11943. if (pickResult.hit && pickResult.pickedSprite) {
  11944. if (pickResult.pickedSprite.actionManager) {
  11945. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11946. }
  11947. }
  11948. }
  11949. };
  11950. this._onKeyDown = function (evt) {
  11951. if (_this.actionManager) {
  11952. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11953. }
  11954. };
  11955. this._onKeyUp = function (evt) {
  11956. if (_this.actionManager) {
  11957. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11958. }
  11959. };
  11960. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11961. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11962. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11963. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11964. // Wheel
  11965. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11966. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11967. BABYLON.Tools.RegisterTopRootEvents([
  11968. { name: "keydown", handler: this._onKeyDown },
  11969. { name: "keyup", handler: this._onKeyUp }
  11970. ]);
  11971. };
  11972. Scene.prototype.detachControl = function () {
  11973. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11974. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11975. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11976. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11977. // Wheel
  11978. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11979. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11980. BABYLON.Tools.UnregisterTopRootEvents([
  11981. { name: "keydown", handler: this._onKeyDown },
  11982. { name: "keyup", handler: this._onKeyUp }
  11983. ]);
  11984. };
  11985. // Ready
  11986. Scene.prototype.isReady = function () {
  11987. if (this._pendingData.length > 0) {
  11988. return false;
  11989. }
  11990. var index;
  11991. for (index = 0; index < this._geometries.length; index++) {
  11992. var geometry = this._geometries[index];
  11993. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11994. return false;
  11995. }
  11996. }
  11997. for (index = 0; index < this.meshes.length; index++) {
  11998. var mesh = this.meshes[index];
  11999. if (!mesh.isReady()) {
  12000. return false;
  12001. }
  12002. var mat = mesh.material;
  12003. if (mat) {
  12004. if (!mat.isReady(mesh)) {
  12005. return false;
  12006. }
  12007. }
  12008. }
  12009. return true;
  12010. };
  12011. Scene.prototype.resetCachedMaterial = function () {
  12012. this._cachedMaterial = null;
  12013. };
  12014. Scene.prototype.registerBeforeRender = function (func) {
  12015. this._onBeforeRenderCallbacks.push(func);
  12016. };
  12017. Scene.prototype.unregisterBeforeRender = function (func) {
  12018. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12019. if (index > -1) {
  12020. this._onBeforeRenderCallbacks.splice(index, 1);
  12021. }
  12022. };
  12023. Scene.prototype.registerAfterRender = function (func) {
  12024. this._onAfterRenderCallbacks.push(func);
  12025. };
  12026. Scene.prototype.unregisterAfterRender = function (func) {
  12027. var index = this._onAfterRenderCallbacks.indexOf(func);
  12028. if (index > -1) {
  12029. this._onAfterRenderCallbacks.splice(index, 1);
  12030. }
  12031. };
  12032. Scene.prototype._addPendingData = function (data) {
  12033. this._pendingData.push(data);
  12034. };
  12035. Scene.prototype._removePendingData = function (data) {
  12036. var index = this._pendingData.indexOf(data);
  12037. if (index !== -1) {
  12038. this._pendingData.splice(index, 1);
  12039. }
  12040. };
  12041. Scene.prototype.getWaitingItemsCount = function () {
  12042. return this._pendingData.length;
  12043. };
  12044. /**
  12045. * Registers a function to be executed when the scene is ready.
  12046. * @param {Function} func - the function to be executed.
  12047. */
  12048. Scene.prototype.executeWhenReady = function (func) {
  12049. var _this = this;
  12050. this._onReadyCallbacks.push(func);
  12051. if (this._executeWhenReadyTimeoutId !== -1) {
  12052. return;
  12053. }
  12054. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12055. _this._checkIsReady();
  12056. }, 150);
  12057. };
  12058. Scene.prototype._checkIsReady = function () {
  12059. var _this = this;
  12060. if (this.isReady()) {
  12061. this._onReadyCallbacks.forEach(function (func) {
  12062. func();
  12063. });
  12064. this._onReadyCallbacks = [];
  12065. this._executeWhenReadyTimeoutId = -1;
  12066. return;
  12067. }
  12068. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12069. _this._checkIsReady();
  12070. }, 150);
  12071. };
  12072. // Animations
  12073. /**
  12074. * Will start the animation sequence of a given target
  12075. * @param target - the target
  12076. * @param {number} from - from which frame should animation start
  12077. * @param {number} to - till which frame should animation run.
  12078. * @param {boolean} [loop] - should the animation loop
  12079. * @param {number} [speedRatio] - the speed in which to run the animation
  12080. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12081. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12082. * @return {BABYLON.Animatable} the animatable object created for this animation
  12083. * @see BABYLON.Animatable
  12084. * @see http://doc.babylonjs.com/page.php?p=22081
  12085. */
  12086. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12087. if (speedRatio === void 0) { speedRatio = 1.0; }
  12088. this.stopAnimation(target);
  12089. if (!animatable) {
  12090. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12091. }
  12092. // Local animations
  12093. if (target.animations) {
  12094. animatable.appendAnimations(target, target.animations);
  12095. }
  12096. // Children animations
  12097. if (target.getAnimatables) {
  12098. var animatables = target.getAnimatables();
  12099. for (var index = 0; index < animatables.length; index++) {
  12100. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12101. }
  12102. }
  12103. return animatable;
  12104. };
  12105. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12106. if (speedRatio === undefined) {
  12107. speedRatio = 1.0;
  12108. }
  12109. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12110. return animatable;
  12111. };
  12112. Scene.prototype.getAnimatableByTarget = function (target) {
  12113. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12114. if (this._activeAnimatables[index].target === target) {
  12115. return this._activeAnimatables[index];
  12116. }
  12117. }
  12118. return null;
  12119. };
  12120. /**
  12121. * Will stop the animation of the given target
  12122. * @param target - the target
  12123. * @see beginAnimation
  12124. */
  12125. Scene.prototype.stopAnimation = function (target) {
  12126. var animatable = this.getAnimatableByTarget(target);
  12127. if (animatable) {
  12128. animatable.stop();
  12129. }
  12130. };
  12131. Scene.prototype._animate = function () {
  12132. if (!this.animationsEnabled) {
  12133. return;
  12134. }
  12135. if (!this._animationStartDate) {
  12136. this._animationStartDate = BABYLON.Tools.Now;
  12137. }
  12138. // Getting time
  12139. var now = BABYLON.Tools.Now;
  12140. var delay = now - this._animationStartDate;
  12141. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12142. this._activeAnimatables[index]._animate(delay);
  12143. }
  12144. };
  12145. // Matrix
  12146. Scene.prototype.getViewMatrix = function () {
  12147. return this._viewMatrix;
  12148. };
  12149. Scene.prototype.getProjectionMatrix = function () {
  12150. return this._projectionMatrix;
  12151. };
  12152. Scene.prototype.getTransformMatrix = function () {
  12153. return this._transformMatrix;
  12154. };
  12155. Scene.prototype.setTransformMatrix = function (view, projection) {
  12156. this._viewMatrix = view;
  12157. this._projectionMatrix = projection;
  12158. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12159. };
  12160. // Methods
  12161. Scene.prototype.addMesh = function (newMesh) {
  12162. newMesh.uniqueId = this._uniqueIdCounter++;
  12163. var position = this.meshes.push(newMesh);
  12164. //notify the collision coordinator
  12165. this.collisionCoordinator.onMeshAdded(newMesh);
  12166. if (this.onNewMeshAdded) {
  12167. this.onNewMeshAdded(newMesh, position, this);
  12168. }
  12169. };
  12170. Scene.prototype.removeMesh = function (toRemove) {
  12171. var index = this.meshes.indexOf(toRemove);
  12172. if (index !== -1) {
  12173. // Remove from the scene if mesh found
  12174. this.meshes.splice(index, 1);
  12175. }
  12176. //notify the collision coordinator
  12177. this.collisionCoordinator.onMeshRemoved(toRemove);
  12178. if (this.onMeshRemoved) {
  12179. this.onMeshRemoved(toRemove);
  12180. }
  12181. return index;
  12182. };
  12183. Scene.prototype.removeSkeleton = function (toRemove) {
  12184. var index = this.skeletons.indexOf(toRemove);
  12185. if (index !== -1) {
  12186. // Remove from the scene if mesh found
  12187. this.skeletons.splice(index, 1);
  12188. }
  12189. return index;
  12190. };
  12191. Scene.prototype.removeLight = function (toRemove) {
  12192. var index = this.lights.indexOf(toRemove);
  12193. if (index !== -1) {
  12194. // Remove from the scene if mesh found
  12195. this.lights.splice(index, 1);
  12196. }
  12197. if (this.onLightRemoved) {
  12198. this.onLightRemoved(toRemove);
  12199. }
  12200. return index;
  12201. };
  12202. Scene.prototype.removeCamera = function (toRemove) {
  12203. var index = this.cameras.indexOf(toRemove);
  12204. if (index !== -1) {
  12205. // Remove from the scene if mesh found
  12206. this.cameras.splice(index, 1);
  12207. }
  12208. // Remove from activeCameras
  12209. var index2 = this.activeCameras.indexOf(toRemove);
  12210. if (index2 !== -1) {
  12211. // Remove from the scene if mesh found
  12212. this.activeCameras.splice(index2, 1);
  12213. }
  12214. // Reset the activeCamera
  12215. if (this.activeCamera === toRemove) {
  12216. if (this.cameras.length > 0) {
  12217. this.activeCamera = this.cameras[0];
  12218. }
  12219. else {
  12220. this.activeCamera = null;
  12221. }
  12222. }
  12223. if (this.onCameraRemoved) {
  12224. this.onCameraRemoved(toRemove);
  12225. }
  12226. return index;
  12227. };
  12228. Scene.prototype.addLight = function (newLight) {
  12229. newLight.uniqueId = this._uniqueIdCounter++;
  12230. var position = this.lights.push(newLight);
  12231. if (this.onNewLightAdded) {
  12232. this.onNewLightAdded(newLight, position, this);
  12233. }
  12234. };
  12235. Scene.prototype.addCamera = function (newCamera) {
  12236. newCamera.uniqueId = this._uniqueIdCounter++;
  12237. var position = this.cameras.push(newCamera);
  12238. if (this.onNewCameraAdded) {
  12239. this.onNewCameraAdded(newCamera, position, this);
  12240. }
  12241. };
  12242. /**
  12243. * sets the active camera of the scene using its ID
  12244. * @param {string} id - the camera's ID
  12245. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12246. * @see activeCamera
  12247. */
  12248. Scene.prototype.setActiveCameraByID = function (id) {
  12249. var camera = this.getCameraByID(id);
  12250. if (camera) {
  12251. this.activeCamera = camera;
  12252. return camera;
  12253. }
  12254. return null;
  12255. };
  12256. /**
  12257. * sets the active camera of the scene using its name
  12258. * @param {string} name - the camera's name
  12259. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12260. * @see activeCamera
  12261. */
  12262. Scene.prototype.setActiveCameraByName = function (name) {
  12263. var camera = this.getCameraByName(name);
  12264. if (camera) {
  12265. this.activeCamera = camera;
  12266. return camera;
  12267. }
  12268. return null;
  12269. };
  12270. /**
  12271. * get a material using its id
  12272. * @param {string} the material's ID
  12273. * @return {BABYLON.Material|null} the material or null if none found.
  12274. */
  12275. Scene.prototype.getMaterialByID = function (id) {
  12276. for (var index = 0; index < this.materials.length; index++) {
  12277. if (this.materials[index].id === id) {
  12278. return this.materials[index];
  12279. }
  12280. }
  12281. return null;
  12282. };
  12283. /**
  12284. * get a material using its name
  12285. * @param {string} the material's name
  12286. * @return {BABYLON.Material|null} the material or null if none found.
  12287. */
  12288. Scene.prototype.getMaterialByName = function (name) {
  12289. for (var index = 0; index < this.materials.length; index++) {
  12290. if (this.materials[index].name === name) {
  12291. return this.materials[index];
  12292. }
  12293. }
  12294. return null;
  12295. };
  12296. Scene.prototype.getLensFlareSystemByName = function (name) {
  12297. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12298. if (this.lensFlareSystems[index].name === name) {
  12299. return this.lensFlareSystems[index];
  12300. }
  12301. }
  12302. return null;
  12303. };
  12304. Scene.prototype.getCameraByID = function (id) {
  12305. for (var index = 0; index < this.cameras.length; index++) {
  12306. if (this.cameras[index].id === id) {
  12307. return this.cameras[index];
  12308. }
  12309. }
  12310. return null;
  12311. };
  12312. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12313. for (var index = 0; index < this.cameras.length; index++) {
  12314. if (this.cameras[index].uniqueId === uniqueId) {
  12315. return this.cameras[index];
  12316. }
  12317. }
  12318. return null;
  12319. };
  12320. /**
  12321. * get a camera using its name
  12322. * @param {string} the camera's name
  12323. * @return {BABYLON.Camera|null} the camera or null if none found.
  12324. */
  12325. Scene.prototype.getCameraByName = function (name) {
  12326. for (var index = 0; index < this.cameras.length; index++) {
  12327. if (this.cameras[index].name === name) {
  12328. return this.cameras[index];
  12329. }
  12330. }
  12331. return null;
  12332. };
  12333. /**
  12334. * get a light node using its name
  12335. * @param {string} the light's name
  12336. * @return {BABYLON.Light|null} the light or null if none found.
  12337. */
  12338. Scene.prototype.getLightByName = function (name) {
  12339. for (var index = 0; index < this.lights.length; index++) {
  12340. if (this.lights[index].name === name) {
  12341. return this.lights[index];
  12342. }
  12343. }
  12344. return null;
  12345. };
  12346. /**
  12347. * get a light node using its ID
  12348. * @param {string} the light's id
  12349. * @return {BABYLON.Light|null} the light or null if none found.
  12350. */
  12351. Scene.prototype.getLightByID = function (id) {
  12352. for (var index = 0; index < this.lights.length; index++) {
  12353. if (this.lights[index].id === id) {
  12354. return this.lights[index];
  12355. }
  12356. }
  12357. return null;
  12358. };
  12359. /**
  12360. * get a light node using its scene-generated unique ID
  12361. * @param {number} the light's unique id
  12362. * @return {BABYLON.Light|null} the light or null if none found.
  12363. */
  12364. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12365. for (var index = 0; index < this.lights.length; index++) {
  12366. if (this.lights[index].uniqueId === uniqueId) {
  12367. return this.lights[index];
  12368. }
  12369. }
  12370. return null;
  12371. };
  12372. /**
  12373. * get a geometry using its ID
  12374. * @param {string} the geometry's id
  12375. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12376. */
  12377. Scene.prototype.getGeometryByID = function (id) {
  12378. for (var index = 0; index < this._geometries.length; index++) {
  12379. if (this._geometries[index].id === id) {
  12380. return this._geometries[index];
  12381. }
  12382. }
  12383. return null;
  12384. };
  12385. /**
  12386. * add a new geometry to this scene.
  12387. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12388. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12389. * @return {boolean} was the geometry added or not
  12390. */
  12391. Scene.prototype.pushGeometry = function (geometry, force) {
  12392. if (!force && this.getGeometryByID(geometry.id)) {
  12393. return false;
  12394. }
  12395. this._geometries.push(geometry);
  12396. //notify the collision coordinator
  12397. this.collisionCoordinator.onGeometryAdded(geometry);
  12398. if (this.onGeometryAdded) {
  12399. this.onGeometryAdded(geometry);
  12400. }
  12401. return true;
  12402. };
  12403. /**
  12404. * Removes an existing geometry
  12405. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12406. * @return {boolean} was the geometry removed or not
  12407. */
  12408. Scene.prototype.removeGeometry = function (geometry) {
  12409. var index = this._geometries.indexOf(geometry);
  12410. if (index > -1) {
  12411. this._geometries.splice(index, 1);
  12412. //notify the collision coordinator
  12413. this.collisionCoordinator.onGeometryDeleted(geometry);
  12414. if (this.onGeometryRemoved) {
  12415. this.onGeometryRemoved(geometry);
  12416. }
  12417. return true;
  12418. }
  12419. return false;
  12420. };
  12421. Scene.prototype.getGeometries = function () {
  12422. return this._geometries;
  12423. };
  12424. /**
  12425. * Get the first added mesh found of a given ID
  12426. * @param {string} id - the id to search for
  12427. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12428. */
  12429. Scene.prototype.getMeshByID = function (id) {
  12430. for (var index = 0; index < this.meshes.length; index++) {
  12431. if (this.meshes[index].id === id) {
  12432. return this.meshes[index];
  12433. }
  12434. }
  12435. return null;
  12436. };
  12437. /**
  12438. * Get a mesh with its auto-generated unique id
  12439. * @param {number} uniqueId - the unique id to search for
  12440. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12441. */
  12442. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12443. for (var index = 0; index < this.meshes.length; index++) {
  12444. if (this.meshes[index].uniqueId === uniqueId) {
  12445. return this.meshes[index];
  12446. }
  12447. }
  12448. return null;
  12449. };
  12450. /**
  12451. * Get a the last added mesh found of a given ID
  12452. * @param {string} id - the id to search for
  12453. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12454. */
  12455. Scene.prototype.getLastMeshByID = function (id) {
  12456. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12457. if (this.meshes[index].id === id) {
  12458. return this.meshes[index];
  12459. }
  12460. }
  12461. return null;
  12462. };
  12463. /**
  12464. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12465. * @param {string} id - the id to search for
  12466. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12467. */
  12468. Scene.prototype.getLastEntryByID = function (id) {
  12469. var index;
  12470. for (index = this.meshes.length - 1; index >= 0; index--) {
  12471. if (this.meshes[index].id === id) {
  12472. return this.meshes[index];
  12473. }
  12474. }
  12475. for (index = this.cameras.length - 1; index >= 0; index--) {
  12476. if (this.cameras[index].id === id) {
  12477. return this.cameras[index];
  12478. }
  12479. }
  12480. for (index = this.lights.length - 1; index >= 0; index--) {
  12481. if (this.lights[index].id === id) {
  12482. return this.lights[index];
  12483. }
  12484. }
  12485. return null;
  12486. };
  12487. Scene.prototype.getNodeByID = function (id) {
  12488. var mesh = this.getMeshByID(id);
  12489. if (mesh) {
  12490. return mesh;
  12491. }
  12492. var light = this.getLightByID(id);
  12493. if (light) {
  12494. return light;
  12495. }
  12496. return this.getCameraByID(id);
  12497. };
  12498. Scene.prototype.getNodeByName = function (name) {
  12499. var mesh = this.getMeshByName(name);
  12500. if (mesh) {
  12501. return mesh;
  12502. }
  12503. var light = this.getLightByName(name);
  12504. if (light) {
  12505. return light;
  12506. }
  12507. return this.getCameraByName(name);
  12508. };
  12509. Scene.prototype.getMeshByName = function (name) {
  12510. for (var index = 0; index < this.meshes.length; index++) {
  12511. if (this.meshes[index].name === name) {
  12512. return this.meshes[index];
  12513. }
  12514. }
  12515. return null;
  12516. };
  12517. Scene.prototype.getSoundByName = function (name) {
  12518. var index;
  12519. if (BABYLON.AudioEngine) {
  12520. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12521. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12522. return this.mainSoundTrack.soundCollection[index];
  12523. }
  12524. }
  12525. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12526. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12527. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12528. return this.soundTracks[sdIndex].soundCollection[index];
  12529. }
  12530. }
  12531. }
  12532. }
  12533. return null;
  12534. };
  12535. Scene.prototype.getLastSkeletonByID = function (id) {
  12536. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12537. if (this.skeletons[index].id === id) {
  12538. return this.skeletons[index];
  12539. }
  12540. }
  12541. return null;
  12542. };
  12543. Scene.prototype.getSkeletonById = function (id) {
  12544. for (var index = 0; index < this.skeletons.length; index++) {
  12545. if (this.skeletons[index].id === id) {
  12546. return this.skeletons[index];
  12547. }
  12548. }
  12549. return null;
  12550. };
  12551. Scene.prototype.getSkeletonByName = function (name) {
  12552. for (var index = 0; index < this.skeletons.length; index++) {
  12553. if (this.skeletons[index].name === name) {
  12554. return this.skeletons[index];
  12555. }
  12556. }
  12557. return null;
  12558. };
  12559. Scene.prototype.isActiveMesh = function (mesh) {
  12560. return (this._activeMeshes.indexOf(mesh) !== -1);
  12561. };
  12562. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12563. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12564. var material = subMesh.getMaterial();
  12565. if (mesh.showSubMeshesBoundingBox) {
  12566. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12567. }
  12568. if (material) {
  12569. // Render targets
  12570. if (material.getRenderTargetTextures) {
  12571. if (this._processedMaterials.indexOf(material) === -1) {
  12572. this._processedMaterials.push(material);
  12573. this._renderTargets.concat(material.getRenderTargetTextures());
  12574. }
  12575. }
  12576. // Dispatch
  12577. this._activeIndices += subMesh.indexCount;
  12578. this._renderingManager.dispatch(subMesh);
  12579. }
  12580. }
  12581. };
  12582. Scene.prototype._evaluateActiveMeshes = function () {
  12583. this.activeCamera._activeMeshes.reset();
  12584. this._activeMeshes.reset();
  12585. this._renderingManager.reset();
  12586. this._processedMaterials.reset();
  12587. this._activeParticleSystems.reset();
  12588. this._activeSkeletons.reset();
  12589. this._softwareSkinnedMeshes.reset();
  12590. this._boundingBoxRenderer.reset();
  12591. this._edgesRenderers.reset();
  12592. if (!this._frustumPlanes) {
  12593. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12594. }
  12595. else {
  12596. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12597. }
  12598. // Meshes
  12599. var meshes;
  12600. var len;
  12601. if (this._selectionOctree) {
  12602. var selection = this._selectionOctree.select(this._frustumPlanes);
  12603. meshes = selection.data;
  12604. len = selection.length;
  12605. }
  12606. else {
  12607. len = this.meshes.length;
  12608. meshes = this.meshes;
  12609. }
  12610. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12611. var mesh = meshes[meshIndex];
  12612. if (mesh.isBlocked) {
  12613. continue;
  12614. }
  12615. this._totalVertices += mesh.getTotalVertices();
  12616. if (!mesh.isReady() || !mesh.isEnabled()) {
  12617. continue;
  12618. }
  12619. mesh.computeWorldMatrix();
  12620. // Intersections
  12621. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12622. this._meshesForIntersections.pushNoDuplicate(mesh);
  12623. }
  12624. // Switch to current LOD
  12625. var meshLOD = mesh.getLOD(this.activeCamera);
  12626. if (!meshLOD) {
  12627. continue;
  12628. }
  12629. mesh._preActivate();
  12630. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12631. this._activeMeshes.push(mesh);
  12632. this.activeCamera._activeMeshes.push(mesh);
  12633. mesh._activate(this._renderId);
  12634. this._activeMesh(meshLOD);
  12635. }
  12636. }
  12637. // Particle systems
  12638. var beforeParticlesDate = BABYLON.Tools.Now;
  12639. if (this.particlesEnabled) {
  12640. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12641. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12642. var particleSystem = this.particleSystems[particleIndex];
  12643. if (!particleSystem.isStarted()) {
  12644. continue;
  12645. }
  12646. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12647. this._activeParticleSystems.push(particleSystem);
  12648. particleSystem.animate();
  12649. }
  12650. }
  12651. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12652. }
  12653. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12654. };
  12655. Scene.prototype._activeMesh = function (mesh) {
  12656. if (mesh.skeleton && this.skeletonsEnabled) {
  12657. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12658. if (!mesh.computeBonesUsingShaders) {
  12659. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12660. }
  12661. }
  12662. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12663. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12664. }
  12665. if (mesh._edgesRenderer) {
  12666. this._edgesRenderers.push(mesh._edgesRenderer);
  12667. }
  12668. if (mesh && mesh.subMeshes) {
  12669. // Submeshes Octrees
  12670. var len;
  12671. var subMeshes;
  12672. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12673. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12674. len = intersections.length;
  12675. subMeshes = intersections.data;
  12676. }
  12677. else {
  12678. subMeshes = mesh.subMeshes;
  12679. len = subMeshes.length;
  12680. }
  12681. for (var subIndex = 0; subIndex < len; subIndex++) {
  12682. var subMesh = subMeshes[subIndex];
  12683. this._evaluateSubMesh(subMesh, mesh);
  12684. }
  12685. }
  12686. };
  12687. Scene.prototype.updateTransformMatrix = function (force) {
  12688. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12689. };
  12690. Scene.prototype._renderForCamera = function (camera) {
  12691. var engine = this._engine;
  12692. this.activeCamera = camera;
  12693. if (!this.activeCamera)
  12694. throw new Error("Active camera not set");
  12695. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12696. // Viewport
  12697. engine.setViewport(this.activeCamera.viewport);
  12698. // Camera
  12699. this.resetCachedMaterial();
  12700. this._renderId++;
  12701. this.updateTransformMatrix();
  12702. if (this.beforeCameraRender) {
  12703. this.beforeCameraRender(this.activeCamera);
  12704. }
  12705. // Meshes
  12706. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12707. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12708. this._evaluateActiveMeshes();
  12709. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12710. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12711. // Skeletons
  12712. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12713. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12714. skeleton.prepare();
  12715. }
  12716. // Software skinning
  12717. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12718. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12719. mesh.applySkeleton(mesh.skeleton);
  12720. }
  12721. // Render targets
  12722. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12723. if (this.renderTargetsEnabled) {
  12724. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12725. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12726. var renderTarget = this._renderTargets.data[renderIndex];
  12727. if (renderTarget._shouldRender()) {
  12728. this._renderId++;
  12729. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12730. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12731. }
  12732. }
  12733. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12734. this._renderId++;
  12735. }
  12736. if (this._renderTargets.length > 0) {
  12737. engine.restoreDefaultFramebuffer();
  12738. }
  12739. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12740. // Prepare Frame
  12741. this.postProcessManager._prepareFrame();
  12742. var beforeRenderDate = BABYLON.Tools.Now;
  12743. // Backgrounds
  12744. var layerIndex;
  12745. var layer;
  12746. if (this.layers.length) {
  12747. engine.setDepthBuffer(false);
  12748. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12749. layer = this.layers[layerIndex];
  12750. if (layer.isBackground) {
  12751. layer.render();
  12752. }
  12753. }
  12754. engine.setDepthBuffer(true);
  12755. }
  12756. // Render
  12757. BABYLON.Tools.StartPerformanceCounter("Main render");
  12758. this._renderingManager.render(null, null, true, true);
  12759. BABYLON.Tools.EndPerformanceCounter("Main render");
  12760. // Bounding boxes
  12761. this._boundingBoxRenderer.render();
  12762. // Edges
  12763. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12764. this._edgesRenderers.data[edgesRendererIndex].render();
  12765. }
  12766. // Lens flares
  12767. if (this.lensFlaresEnabled) {
  12768. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12769. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12770. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12771. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12772. lensFlareSystem.render();
  12773. }
  12774. }
  12775. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12776. }
  12777. // Foregrounds
  12778. if (this.layers.length) {
  12779. engine.setDepthBuffer(false);
  12780. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12781. layer = this.layers[layerIndex];
  12782. if (!layer.isBackground) {
  12783. layer.render();
  12784. }
  12785. }
  12786. engine.setDepthBuffer(true);
  12787. }
  12788. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12789. // Finalize frame
  12790. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12791. // Update camera
  12792. this.activeCamera._updateFromScene();
  12793. // Reset some special arrays
  12794. this._renderTargets.reset();
  12795. if (this.afterCameraRender) {
  12796. this.afterCameraRender(this.activeCamera);
  12797. }
  12798. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12799. };
  12800. Scene.prototype._processSubCameras = function (camera) {
  12801. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12802. this._renderForCamera(camera);
  12803. return;
  12804. }
  12805. // rig cameras
  12806. for (var index = 0; index < camera._rigCameras.length; index++) {
  12807. this._renderForCamera(camera._rigCameras[index]);
  12808. }
  12809. this.activeCamera = camera;
  12810. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12811. // Update camera
  12812. this.activeCamera._updateFromScene();
  12813. };
  12814. Scene.prototype._checkIntersections = function () {
  12815. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12816. var sourceMesh = this._meshesForIntersections.data[index];
  12817. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12818. var action = sourceMesh.actionManager.actions[actionIndex];
  12819. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12820. var parameters = action.getTriggerParameter();
  12821. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12822. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12823. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12824. if (areIntersecting && currentIntersectionInProgress === -1) {
  12825. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12826. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12827. sourceMesh._intersectionsInProgress.push(otherMesh);
  12828. }
  12829. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12830. sourceMesh._intersectionsInProgress.push(otherMesh);
  12831. }
  12832. }
  12833. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12834. //They intersected, and now they don't.
  12835. //is this trigger an exit trigger? execute an event.
  12836. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12837. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12838. }
  12839. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12840. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12841. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12842. }
  12843. }
  12844. }
  12845. }
  12846. }
  12847. };
  12848. Scene.prototype.render = function () {
  12849. var startDate = BABYLON.Tools.Now;
  12850. this._particlesDuration = 0;
  12851. this._spritesDuration = 0;
  12852. this._activeParticles = 0;
  12853. this._renderDuration = 0;
  12854. this._renderTargetsDuration = 0;
  12855. this._evaluateActiveMeshesDuration = 0;
  12856. this._totalVertices = 0;
  12857. this._activeIndices = 0;
  12858. this._activeBones = 0;
  12859. this.getEngine().resetDrawCalls();
  12860. this._meshesForIntersections.reset();
  12861. this.resetCachedMaterial();
  12862. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12863. // Actions
  12864. if (this.actionManager) {
  12865. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12866. }
  12867. //Simplification Queue
  12868. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12869. this.simplificationQueue.executeNext();
  12870. }
  12871. // Animations
  12872. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12873. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12874. this._animate();
  12875. // Physics
  12876. if (this._physicsEngine) {
  12877. BABYLON.Tools.StartPerformanceCounter("Physics");
  12878. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12879. BABYLON.Tools.EndPerformanceCounter("Physics");
  12880. }
  12881. // Before render
  12882. if (this.beforeRender) {
  12883. this.beforeRender();
  12884. }
  12885. var callbackIndex;
  12886. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12887. this._onBeforeRenderCallbacks[callbackIndex]();
  12888. }
  12889. // Customs render targets
  12890. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12891. var engine = this.getEngine();
  12892. var currentActiveCamera = this.activeCamera;
  12893. if (this.renderTargetsEnabled) {
  12894. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12895. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12896. var renderTarget = this.customRenderTargets[customIndex];
  12897. if (renderTarget._shouldRender()) {
  12898. this._renderId++;
  12899. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12900. if (!this.activeCamera)
  12901. throw new Error("Active camera not set");
  12902. // Viewport
  12903. engine.setViewport(this.activeCamera.viewport);
  12904. // Camera
  12905. this.updateTransformMatrix();
  12906. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12907. }
  12908. }
  12909. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12910. this._renderId++;
  12911. }
  12912. if (this.customRenderTargets.length > 0) {
  12913. engine.restoreDefaultFramebuffer();
  12914. }
  12915. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12916. this.activeCamera = currentActiveCamera;
  12917. // Procedural textures
  12918. if (this.proceduralTexturesEnabled) {
  12919. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12920. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12921. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12922. if (proceduralTexture._shouldRender()) {
  12923. proceduralTexture.render();
  12924. }
  12925. }
  12926. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12927. }
  12928. // Clear
  12929. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12930. // Shadows
  12931. if (this.shadowsEnabled) {
  12932. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12933. var light = this.lights[lightIndex];
  12934. var shadowGenerator = light.getShadowGenerator();
  12935. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12936. this._renderTargets.push(shadowGenerator.getShadowMap());
  12937. }
  12938. }
  12939. }
  12940. // Depth renderer
  12941. if (this._depthRenderer) {
  12942. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12943. }
  12944. // RenderPipeline
  12945. this.postProcessRenderPipelineManager.update();
  12946. // Multi-cameras?
  12947. if (this.activeCameras.length > 0) {
  12948. var currentRenderId = this._renderId;
  12949. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12950. this._renderId = currentRenderId;
  12951. this._processSubCameras(this.activeCameras[cameraIndex]);
  12952. }
  12953. }
  12954. else {
  12955. if (!this.activeCamera) {
  12956. throw new Error("No camera defined");
  12957. }
  12958. this._processSubCameras(this.activeCamera);
  12959. }
  12960. // Intersection checks
  12961. this._checkIntersections();
  12962. // Update the audio listener attached to the camera
  12963. if (BABYLON.AudioEngine) {
  12964. this._updateAudioParameters();
  12965. }
  12966. // After render
  12967. if (this.afterRender) {
  12968. this.afterRender();
  12969. }
  12970. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12971. this._onAfterRenderCallbacks[callbackIndex]();
  12972. }
  12973. // Cleaning
  12974. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12975. this._toBeDisposed.data[index].dispose();
  12976. this._toBeDisposed[index] = null;
  12977. }
  12978. this._toBeDisposed.reset();
  12979. if (this.dumpNextRenderTargets) {
  12980. this.dumpNextRenderTargets = false;
  12981. }
  12982. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12983. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12984. };
  12985. Scene.prototype._updateAudioParameters = function () {
  12986. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12987. return;
  12988. }
  12989. var listeningCamera;
  12990. var audioEngine = BABYLON.Engine.audioEngine;
  12991. if (this.activeCameras.length > 0) {
  12992. listeningCamera = this.activeCameras[0];
  12993. }
  12994. else {
  12995. listeningCamera = this.activeCamera;
  12996. }
  12997. if (listeningCamera && audioEngine.canUseWebAudio) {
  12998. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12999. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13000. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13001. cameraDirection.normalize();
  13002. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13003. var i;
  13004. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13005. var sound = this.mainSoundTrack.soundCollection[i];
  13006. if (sound.useCustomAttenuation) {
  13007. sound.updateDistanceFromListener();
  13008. }
  13009. }
  13010. for (i = 0; i < this.soundTracks.length; i++) {
  13011. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13012. sound = this.soundTracks[i].soundCollection[j];
  13013. if (sound.useCustomAttenuation) {
  13014. sound.updateDistanceFromListener();
  13015. }
  13016. }
  13017. }
  13018. }
  13019. };
  13020. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13021. // Audio
  13022. get: function () {
  13023. return this._audioEnabled;
  13024. },
  13025. set: function (value) {
  13026. this._audioEnabled = value;
  13027. if (BABYLON.AudioEngine) {
  13028. if (this._audioEnabled) {
  13029. this._enableAudio();
  13030. }
  13031. else {
  13032. this._disableAudio();
  13033. }
  13034. }
  13035. },
  13036. enumerable: true,
  13037. configurable: true
  13038. });
  13039. Scene.prototype._disableAudio = function () {
  13040. var i;
  13041. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13042. this.mainSoundTrack.soundCollection[i].pause();
  13043. }
  13044. for (i = 0; i < this.soundTracks.length; i++) {
  13045. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13046. this.soundTracks[i].soundCollection[j].pause();
  13047. }
  13048. }
  13049. };
  13050. Scene.prototype._enableAudio = function () {
  13051. var i;
  13052. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13053. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13054. this.mainSoundTrack.soundCollection[i].play();
  13055. }
  13056. }
  13057. for (i = 0; i < this.soundTracks.length; i++) {
  13058. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13059. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13060. this.soundTracks[i].soundCollection[j].play();
  13061. }
  13062. }
  13063. }
  13064. };
  13065. Object.defineProperty(Scene.prototype, "headphone", {
  13066. get: function () {
  13067. return this._headphone;
  13068. },
  13069. set: function (value) {
  13070. this._headphone = value;
  13071. if (BABYLON.AudioEngine) {
  13072. if (this._headphone) {
  13073. this._switchAudioModeForHeadphones();
  13074. }
  13075. else {
  13076. this._switchAudioModeForNormalSpeakers();
  13077. }
  13078. }
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Scene.prototype._switchAudioModeForHeadphones = function () {
  13084. this.mainSoundTrack.switchPanningModelToHRTF();
  13085. for (var i = 0; i < this.soundTracks.length; i++) {
  13086. this.soundTracks[i].switchPanningModelToHRTF();
  13087. }
  13088. };
  13089. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13090. this.mainSoundTrack.switchPanningModelToEqualPower();
  13091. for (var i = 0; i < this.soundTracks.length; i++) {
  13092. this.soundTracks[i].switchPanningModelToEqualPower();
  13093. }
  13094. };
  13095. Scene.prototype.enableDepthRenderer = function () {
  13096. if (this._depthRenderer) {
  13097. return this._depthRenderer;
  13098. }
  13099. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13100. return this._depthRenderer;
  13101. };
  13102. Scene.prototype.disableDepthRenderer = function () {
  13103. if (!this._depthRenderer) {
  13104. return;
  13105. }
  13106. this._depthRenderer.dispose();
  13107. this._depthRenderer = null;
  13108. };
  13109. Scene.prototype.dispose = function () {
  13110. this.beforeRender = null;
  13111. this.afterRender = null;
  13112. this.skeletons = [];
  13113. this._boundingBoxRenderer.dispose();
  13114. if (this._depthRenderer) {
  13115. this._depthRenderer.dispose();
  13116. }
  13117. // Debug layer
  13118. this.debugLayer.hide();
  13119. // Events
  13120. if (this.onDispose) {
  13121. this.onDispose();
  13122. }
  13123. this._onBeforeRenderCallbacks = [];
  13124. this._onAfterRenderCallbacks = [];
  13125. this.detachControl();
  13126. // Release sounds & sounds tracks
  13127. if (BABYLON.AudioEngine) {
  13128. this.disposeSounds();
  13129. }
  13130. // Detach cameras
  13131. var canvas = this._engine.getRenderingCanvas();
  13132. var index;
  13133. for (index = 0; index < this.cameras.length; index++) {
  13134. this.cameras[index].detachControl(canvas);
  13135. }
  13136. // Release lights
  13137. while (this.lights.length) {
  13138. this.lights[0].dispose();
  13139. }
  13140. // Release meshes
  13141. while (this.meshes.length) {
  13142. this.meshes[0].dispose(true);
  13143. }
  13144. // Release cameras
  13145. while (this.cameras.length) {
  13146. this.cameras[0].dispose();
  13147. }
  13148. // Release materials
  13149. while (this.materials.length) {
  13150. this.materials[0].dispose();
  13151. }
  13152. // Release particles
  13153. while (this.particleSystems.length) {
  13154. this.particleSystems[0].dispose();
  13155. }
  13156. // Release sprites
  13157. while (this.spriteManagers.length) {
  13158. this.spriteManagers[0].dispose();
  13159. }
  13160. // Release layers
  13161. while (this.layers.length) {
  13162. this.layers[0].dispose();
  13163. }
  13164. // Release textures
  13165. while (this.textures.length) {
  13166. this.textures[0].dispose();
  13167. }
  13168. // Post-processes
  13169. this.postProcessManager.dispose();
  13170. // Physics
  13171. if (this._physicsEngine) {
  13172. this.disablePhysicsEngine();
  13173. }
  13174. // Remove from engine
  13175. index = this._engine.scenes.indexOf(this);
  13176. if (index > -1) {
  13177. this._engine.scenes.splice(index, 1);
  13178. }
  13179. this._engine.wipeCaches();
  13180. };
  13181. // Release sounds & sounds tracks
  13182. Scene.prototype.disposeSounds = function () {
  13183. this.mainSoundTrack.dispose();
  13184. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13185. this.soundTracks[scIndex].dispose();
  13186. }
  13187. };
  13188. // Octrees
  13189. Scene.prototype.getWorldExtends = function () {
  13190. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13191. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13192. for (var index = 0; index < this.meshes.length; index++) {
  13193. var mesh = this.meshes[index];
  13194. mesh.computeWorldMatrix(true);
  13195. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13196. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13197. BABYLON.Tools.CheckExtends(minBox, min, max);
  13198. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13199. }
  13200. return {
  13201. min: min,
  13202. max: max
  13203. };
  13204. };
  13205. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13206. if (maxCapacity === void 0) { maxCapacity = 64; }
  13207. if (maxDepth === void 0) { maxDepth = 2; }
  13208. if (!this._selectionOctree) {
  13209. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13210. }
  13211. var worldExtends = this.getWorldExtends();
  13212. // Update octree
  13213. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13214. return this._selectionOctree;
  13215. };
  13216. // Picking
  13217. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13218. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13219. var engine = this._engine;
  13220. if (!camera) {
  13221. if (!this.activeCamera)
  13222. throw new Error("Active camera not set");
  13223. camera = this.activeCamera;
  13224. }
  13225. var cameraViewport = camera.viewport;
  13226. var viewport = cameraViewport.toGlobal(engine);
  13227. // Moving coordinates to local viewport world
  13228. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13229. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13230. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13231. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13232. };
  13233. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13234. var engine = this._engine;
  13235. if (!camera) {
  13236. if (!this.activeCamera)
  13237. throw new Error("Active camera not set");
  13238. camera = this.activeCamera;
  13239. }
  13240. var cameraViewport = camera.viewport;
  13241. var viewport = cameraViewport.toGlobal(engine);
  13242. var identity = BABYLON.Matrix.Identity();
  13243. // Moving coordinates to local viewport world
  13244. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13245. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13246. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13247. };
  13248. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13249. var pickingInfo = null;
  13250. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13251. var mesh = this.meshes[meshIndex];
  13252. if (predicate) {
  13253. if (!predicate(mesh)) {
  13254. continue;
  13255. }
  13256. }
  13257. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13258. continue;
  13259. }
  13260. var world = mesh.getWorldMatrix();
  13261. var ray = rayFunction(world);
  13262. var result = mesh.intersects(ray, fastCheck);
  13263. if (!result || !result.hit)
  13264. continue;
  13265. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13266. continue;
  13267. pickingInfo = result;
  13268. if (fastCheck) {
  13269. break;
  13270. }
  13271. }
  13272. return pickingInfo || new BABYLON.PickingInfo();
  13273. };
  13274. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13275. var pickingInfo = null;
  13276. camera = camera || this.activeCamera;
  13277. if (this.spriteManagers.length > 0) {
  13278. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13279. var spriteManager = this.spriteManagers[spriteIndex];
  13280. if (!spriteManager.isPickable) {
  13281. continue;
  13282. }
  13283. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13284. if (!result || !result.hit)
  13285. continue;
  13286. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13287. continue;
  13288. pickingInfo = result;
  13289. if (fastCheck) {
  13290. break;
  13291. }
  13292. }
  13293. }
  13294. return pickingInfo || new BABYLON.PickingInfo();
  13295. };
  13296. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13297. var _this = this;
  13298. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13299. /// <param name="x">X position on screen</param>
  13300. /// <param name="y">Y position on screen</param>
  13301. /// <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>
  13302. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13303. /// <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>
  13304. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13305. };
  13306. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13307. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13308. /// <param name="x">X position on screen</param>
  13309. /// <param name="y">Y position on screen</param>
  13310. /// <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>
  13311. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13312. /// <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>
  13313. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13314. };
  13315. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13316. var _this = this;
  13317. return this._internalPick(function (world) {
  13318. if (!_this._pickWithRayInverseMatrix) {
  13319. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13320. }
  13321. world.invertToRef(_this._pickWithRayInverseMatrix);
  13322. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13323. }, predicate, fastCheck);
  13324. };
  13325. Scene.prototype.setPointerOverMesh = function (mesh) {
  13326. if (this._pointerOverMesh === mesh) {
  13327. return;
  13328. }
  13329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13331. }
  13332. this._pointerOverMesh = mesh;
  13333. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13334. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13335. }
  13336. };
  13337. Scene.prototype.getPointerOverMesh = function () {
  13338. return this._pointerOverMesh;
  13339. };
  13340. // Physics
  13341. Scene.prototype.getPhysicsEngine = function () {
  13342. return this._physicsEngine;
  13343. };
  13344. /**
  13345. * Enables physics to the current scene
  13346. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13347. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13348. * @return {boolean} was the physics engine initialized
  13349. */
  13350. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13351. if (this._physicsEngine) {
  13352. return true;
  13353. }
  13354. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13355. if (!this._physicsEngine.isSupported()) {
  13356. this._physicsEngine = null;
  13357. return false;
  13358. }
  13359. this._physicsEngine._initialize(gravity);
  13360. return true;
  13361. };
  13362. Scene.prototype.disablePhysicsEngine = function () {
  13363. if (!this._physicsEngine) {
  13364. return;
  13365. }
  13366. this._physicsEngine.dispose();
  13367. this._physicsEngine = undefined;
  13368. };
  13369. Scene.prototype.isPhysicsEnabled = function () {
  13370. return this._physicsEngine !== undefined;
  13371. };
  13372. /**
  13373. * Sets the gravity of the physics engine (and NOT of the scene)
  13374. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13375. */
  13376. Scene.prototype.setGravity = function (gravity) {
  13377. if (!this._physicsEngine) {
  13378. return;
  13379. }
  13380. this._physicsEngine._setGravity(gravity);
  13381. };
  13382. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13383. if (parts.parts) {
  13384. options = parts;
  13385. parts = parts.parts;
  13386. }
  13387. if (!this._physicsEngine) {
  13388. return null;
  13389. }
  13390. for (var index = 0; index < parts.length; index++) {
  13391. var mesh = parts[index].mesh;
  13392. mesh._physicImpostor = parts[index].impostor;
  13393. mesh._physicsMass = options.mass / parts.length;
  13394. mesh._physicsFriction = options.friction;
  13395. mesh._physicRestitution = options.restitution;
  13396. }
  13397. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13398. };
  13399. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13400. for (var index = 0; index < compound.parts.length; index++) {
  13401. var mesh = compound.parts[index].mesh;
  13402. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13403. this._physicsEngine._unregisterMesh(mesh);
  13404. }
  13405. };
  13406. // Misc.
  13407. Scene.prototype.createDefaultCameraOrLight = function () {
  13408. // Light
  13409. if (this.lights.length === 0) {
  13410. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13411. }
  13412. // Camera
  13413. if (!this.activeCamera) {
  13414. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13415. // Compute position
  13416. var worldExtends = this.getWorldExtends();
  13417. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13418. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13419. camera.setTarget(worldCenter);
  13420. this.activeCamera = camera;
  13421. }
  13422. };
  13423. // Tags
  13424. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13425. if (tagsQuery === undefined) {
  13426. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13427. return list;
  13428. }
  13429. var listByTags = [];
  13430. forEach = forEach || (function (item) { return; });
  13431. for (var i in list) {
  13432. var item = list[i];
  13433. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13434. listByTags.push(item);
  13435. forEach(item);
  13436. }
  13437. }
  13438. return listByTags;
  13439. };
  13440. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13441. return this._getByTags(this.meshes, tagsQuery, forEach);
  13442. };
  13443. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13444. return this._getByTags(this.cameras, tagsQuery, forEach);
  13445. };
  13446. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13447. return this._getByTags(this.lights, tagsQuery, forEach);
  13448. };
  13449. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13450. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13451. };
  13452. // Statics
  13453. Scene._FOGMODE_NONE = 0;
  13454. Scene._FOGMODE_EXP = 1;
  13455. Scene._FOGMODE_EXP2 = 2;
  13456. Scene._FOGMODE_LINEAR = 3;
  13457. Scene.MinDeltaTime = 1.0;
  13458. Scene.MaxDeltaTime = 1000.0;
  13459. return Scene;
  13460. })();
  13461. BABYLON.Scene = Scene;
  13462. })(BABYLON || (BABYLON = {}));
  13463. var BABYLON;
  13464. (function (BABYLON) {
  13465. var VertexBuffer = (function () {
  13466. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13467. if (engine instanceof BABYLON.Mesh) {
  13468. this._engine = engine.getScene().getEngine();
  13469. }
  13470. else {
  13471. this._engine = engine;
  13472. }
  13473. this._updatable = updatable;
  13474. this._data = data;
  13475. if (!postponeInternalCreation) {
  13476. this.create();
  13477. }
  13478. this._kind = kind;
  13479. if (stride) {
  13480. this._strideSize = stride;
  13481. return;
  13482. }
  13483. // Deduce stride from kind
  13484. switch (kind) {
  13485. case VertexBuffer.PositionKind:
  13486. this._strideSize = 3;
  13487. break;
  13488. case VertexBuffer.NormalKind:
  13489. this._strideSize = 3;
  13490. break;
  13491. case VertexBuffer.UVKind:
  13492. case VertexBuffer.UV2Kind:
  13493. case VertexBuffer.UV3Kind:
  13494. case VertexBuffer.UV4Kind:
  13495. case VertexBuffer.UV5Kind:
  13496. case VertexBuffer.UV6Kind:
  13497. this._strideSize = 2;
  13498. break;
  13499. case VertexBuffer.ColorKind:
  13500. this._strideSize = 4;
  13501. break;
  13502. case VertexBuffer.MatricesIndicesKind:
  13503. case VertexBuffer.MatricesIndicesExtraKind:
  13504. this._strideSize = 4;
  13505. break;
  13506. case VertexBuffer.MatricesWeightsKind:
  13507. case VertexBuffer.MatricesWeightsExtraKind:
  13508. this._strideSize = 4;
  13509. break;
  13510. }
  13511. }
  13512. // Properties
  13513. VertexBuffer.prototype.isUpdatable = function () {
  13514. return this._updatable;
  13515. };
  13516. VertexBuffer.prototype.getData = function () {
  13517. return this._data;
  13518. };
  13519. VertexBuffer.prototype.getBuffer = function () {
  13520. return this._buffer;
  13521. };
  13522. VertexBuffer.prototype.getStrideSize = function () {
  13523. return this._strideSize;
  13524. };
  13525. // Methods
  13526. VertexBuffer.prototype.create = function (data) {
  13527. if (!data && this._buffer) {
  13528. return; // nothing to do
  13529. }
  13530. data = data || this._data;
  13531. if (!this._buffer) {
  13532. if (this._updatable) {
  13533. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13534. }
  13535. else {
  13536. this._buffer = this._engine.createVertexBuffer(data);
  13537. }
  13538. }
  13539. if (this._updatable) {
  13540. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13541. this._data = data;
  13542. }
  13543. };
  13544. VertexBuffer.prototype.update = function (data) {
  13545. this.create(data);
  13546. };
  13547. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13548. if (!this._buffer) {
  13549. return;
  13550. }
  13551. if (this._updatable) {
  13552. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13553. this._data = null;
  13554. }
  13555. };
  13556. VertexBuffer.prototype.dispose = function () {
  13557. if (!this._buffer) {
  13558. return;
  13559. }
  13560. if (this._engine._releaseBuffer(this._buffer)) {
  13561. this._buffer = null;
  13562. }
  13563. };
  13564. Object.defineProperty(VertexBuffer, "PositionKind", {
  13565. get: function () {
  13566. return VertexBuffer._PositionKind;
  13567. },
  13568. enumerable: true,
  13569. configurable: true
  13570. });
  13571. Object.defineProperty(VertexBuffer, "NormalKind", {
  13572. get: function () {
  13573. return VertexBuffer._NormalKind;
  13574. },
  13575. enumerable: true,
  13576. configurable: true
  13577. });
  13578. Object.defineProperty(VertexBuffer, "UVKind", {
  13579. get: function () {
  13580. return VertexBuffer._UVKind;
  13581. },
  13582. enumerable: true,
  13583. configurable: true
  13584. });
  13585. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13586. get: function () {
  13587. return VertexBuffer._UV2Kind;
  13588. },
  13589. enumerable: true,
  13590. configurable: true
  13591. });
  13592. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13593. get: function () {
  13594. return VertexBuffer._UV3Kind;
  13595. },
  13596. enumerable: true,
  13597. configurable: true
  13598. });
  13599. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13600. get: function () {
  13601. return VertexBuffer._UV4Kind;
  13602. },
  13603. enumerable: true,
  13604. configurable: true
  13605. });
  13606. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13607. get: function () {
  13608. return VertexBuffer._UV5Kind;
  13609. },
  13610. enumerable: true,
  13611. configurable: true
  13612. });
  13613. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13614. get: function () {
  13615. return VertexBuffer._UV6Kind;
  13616. },
  13617. enumerable: true,
  13618. configurable: true
  13619. });
  13620. Object.defineProperty(VertexBuffer, "ColorKind", {
  13621. get: function () {
  13622. return VertexBuffer._ColorKind;
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13628. get: function () {
  13629. return VertexBuffer._MatricesIndicesKind;
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13635. get: function () {
  13636. return VertexBuffer._MatricesWeightsKind;
  13637. },
  13638. enumerable: true,
  13639. configurable: true
  13640. });
  13641. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  13642. get: function () {
  13643. return VertexBuffer._MatricesIndicesExtraKind;
  13644. },
  13645. enumerable: true,
  13646. configurable: true
  13647. });
  13648. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  13649. get: function () {
  13650. return VertexBuffer._MatricesWeightsExtraKind;
  13651. },
  13652. enumerable: true,
  13653. configurable: true
  13654. });
  13655. // Enums
  13656. VertexBuffer._PositionKind = "position";
  13657. VertexBuffer._NormalKind = "normal";
  13658. VertexBuffer._UVKind = "uv";
  13659. VertexBuffer._UV2Kind = "uv2";
  13660. VertexBuffer._UV3Kind = "uv3";
  13661. VertexBuffer._UV4Kind = "uv4";
  13662. VertexBuffer._UV5Kind = "uv5";
  13663. VertexBuffer._UV6Kind = "uv6";
  13664. VertexBuffer._ColorKind = "color";
  13665. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13666. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13667. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  13668. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  13669. return VertexBuffer;
  13670. })();
  13671. BABYLON.VertexBuffer = VertexBuffer;
  13672. })(BABYLON || (BABYLON = {}));
  13673. var BABYLON;
  13674. (function (BABYLON) {
  13675. /**
  13676. * Creates an instance based on a source mesh.
  13677. */
  13678. var InstancedMesh = (function (_super) {
  13679. __extends(InstancedMesh, _super);
  13680. function InstancedMesh(name, source) {
  13681. _super.call(this, name, source.getScene());
  13682. source.instances.push(this);
  13683. this._sourceMesh = source;
  13684. this.position.copyFrom(source.position);
  13685. this.rotation.copyFrom(source.rotation);
  13686. this.scaling.copyFrom(source.scaling);
  13687. if (source.rotationQuaternion) {
  13688. this.rotationQuaternion = source.rotationQuaternion.clone();
  13689. }
  13690. this.infiniteDistance = source.infiniteDistance;
  13691. this.setPivotMatrix(source.getPivotMatrix());
  13692. this.refreshBoundingInfo();
  13693. this._syncSubMeshes();
  13694. }
  13695. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13696. // Methods
  13697. get: function () {
  13698. return this._sourceMesh.receiveShadows;
  13699. },
  13700. enumerable: true,
  13701. configurable: true
  13702. });
  13703. Object.defineProperty(InstancedMesh.prototype, "material", {
  13704. get: function () {
  13705. return this._sourceMesh.material;
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13711. get: function () {
  13712. return this._sourceMesh.visibility;
  13713. },
  13714. enumerable: true,
  13715. configurable: true
  13716. });
  13717. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13718. get: function () {
  13719. return this._sourceMesh.skeleton;
  13720. },
  13721. enumerable: true,
  13722. configurable: true
  13723. });
  13724. InstancedMesh.prototype.getTotalVertices = function () {
  13725. return this._sourceMesh.getTotalVertices();
  13726. };
  13727. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13728. get: function () {
  13729. return this._sourceMesh;
  13730. },
  13731. enumerable: true,
  13732. configurable: true
  13733. });
  13734. InstancedMesh.prototype.getVerticesData = function (kind) {
  13735. return this._sourceMesh.getVerticesData(kind);
  13736. };
  13737. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13738. return this._sourceMesh.isVerticesDataPresent(kind);
  13739. };
  13740. InstancedMesh.prototype.getIndices = function () {
  13741. return this._sourceMesh.getIndices();
  13742. };
  13743. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13744. get: function () {
  13745. return this._sourceMesh._positions;
  13746. },
  13747. enumerable: true,
  13748. configurable: true
  13749. });
  13750. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13751. var meshBB = this._sourceMesh.getBoundingInfo();
  13752. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13753. this._updateBoundingInfo();
  13754. };
  13755. InstancedMesh.prototype._preActivate = function () {
  13756. if (this._currentLOD) {
  13757. this._currentLOD._preActivate();
  13758. }
  13759. };
  13760. InstancedMesh.prototype._activate = function (renderId) {
  13761. if (this._currentLOD) {
  13762. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13763. }
  13764. };
  13765. InstancedMesh.prototype.getLOD = function (camera) {
  13766. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13767. if (this._currentLOD === this.sourceMesh) {
  13768. return this;
  13769. }
  13770. return this._currentLOD;
  13771. };
  13772. InstancedMesh.prototype._syncSubMeshes = function () {
  13773. this.releaseSubMeshes();
  13774. if (this._sourceMesh.subMeshes) {
  13775. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13776. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13777. }
  13778. }
  13779. };
  13780. InstancedMesh.prototype._generatePointsArray = function () {
  13781. return this._sourceMesh._generatePointsArray();
  13782. };
  13783. // Clone
  13784. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13785. var result = this._sourceMesh.createInstance(name);
  13786. // Deep copy
  13787. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13788. // Bounding info
  13789. this.refreshBoundingInfo();
  13790. // Parent
  13791. if (newParent) {
  13792. result.parent = newParent;
  13793. }
  13794. if (!doNotCloneChildren) {
  13795. // Children
  13796. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13797. var mesh = this.getScene().meshes[index];
  13798. if (mesh.parent === this) {
  13799. mesh.clone(mesh.name, result);
  13800. }
  13801. }
  13802. }
  13803. result.computeWorldMatrix(true);
  13804. return result;
  13805. };
  13806. // Dispoe
  13807. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13808. // Remove from mesh
  13809. var index = this._sourceMesh.instances.indexOf(this);
  13810. this._sourceMesh.instances.splice(index, 1);
  13811. _super.prototype.dispose.call(this, doNotRecurse);
  13812. };
  13813. return InstancedMesh;
  13814. })(BABYLON.AbstractMesh);
  13815. BABYLON.InstancedMesh = InstancedMesh;
  13816. })(BABYLON || (BABYLON = {}));
  13817. var BABYLON;
  13818. (function (BABYLON) {
  13819. var _InstancesBatch = (function () {
  13820. function _InstancesBatch() {
  13821. this.mustReturn = false;
  13822. this.visibleInstances = new Array();
  13823. this.renderSelf = new Array();
  13824. }
  13825. return _InstancesBatch;
  13826. })();
  13827. BABYLON._InstancesBatch = _InstancesBatch;
  13828. var Mesh = (function (_super) {
  13829. __extends(Mesh, _super);
  13830. /**
  13831. * @constructor
  13832. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13833. * @param {Scene} scene - The scene to add this mesh to.
  13834. * @param {Node} parent - The parent of this mesh, if it has one
  13835. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13836. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13837. * When false, achieved by calling a clone(), also passing False.
  13838. * This will make creation of children, recursive.
  13839. */
  13840. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13841. if (parent === void 0) { parent = null; }
  13842. _super.call(this, name, scene);
  13843. // Members
  13844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13845. this.instances = new Array();
  13846. this._LODLevels = new Array();
  13847. this._onBeforeRenderCallbacks = new Array();
  13848. this._onAfterRenderCallbacks = new Array();
  13849. this._visibleInstances = {};
  13850. this._renderIdForInstances = new Array();
  13851. this._batchCache = new _InstancesBatch();
  13852. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13853. this._sideOrientation = Mesh._DEFAULTSIDE;
  13854. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13855. if (source) {
  13856. // Geometry
  13857. if (source._geometry) {
  13858. source._geometry.applyToMesh(this);
  13859. }
  13860. // Deep copy
  13861. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13862. this.id = name + "." + source.id;
  13863. // Material
  13864. this.material = source.material;
  13865. var index;
  13866. if (!doNotCloneChildren) {
  13867. // Children
  13868. for (index = 0; index < scene.meshes.length; index++) {
  13869. var mesh = scene.meshes[index];
  13870. if (mesh.parent === source) {
  13871. // doNotCloneChildren is always going to be False
  13872. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13873. }
  13874. }
  13875. }
  13876. // Particles
  13877. for (index = 0; index < scene.particleSystems.length; index++) {
  13878. var system = scene.particleSystems[index];
  13879. if (system.emitter === source) {
  13880. system.clone(system.name, this);
  13881. }
  13882. }
  13883. this.computeWorldMatrix(true);
  13884. }
  13885. // Parent
  13886. if (parent !== null) {
  13887. this.parent = parent;
  13888. }
  13889. }
  13890. Object.defineProperty(Mesh, "FRONTSIDE", {
  13891. get: function () {
  13892. return Mesh._FRONTSIDE;
  13893. },
  13894. enumerable: true,
  13895. configurable: true
  13896. });
  13897. Object.defineProperty(Mesh, "BACKSIDE", {
  13898. get: function () {
  13899. return Mesh._BACKSIDE;
  13900. },
  13901. enumerable: true,
  13902. configurable: true
  13903. });
  13904. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13905. get: function () {
  13906. return Mesh._DOUBLESIDE;
  13907. },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13912. get: function () {
  13913. return Mesh._DEFAULTSIDE;
  13914. },
  13915. enumerable: true,
  13916. configurable: true
  13917. });
  13918. Object.defineProperty(Mesh, "NO_CAP", {
  13919. get: function () {
  13920. return Mesh._NO_CAP;
  13921. },
  13922. enumerable: true,
  13923. configurable: true
  13924. });
  13925. Object.defineProperty(Mesh, "CAP_START", {
  13926. get: function () {
  13927. return Mesh._CAP_START;
  13928. },
  13929. enumerable: true,
  13930. configurable: true
  13931. });
  13932. Object.defineProperty(Mesh, "CAP_END", {
  13933. get: function () {
  13934. return Mesh._CAP_END;
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Object.defineProperty(Mesh, "CAP_ALL", {
  13940. get: function () {
  13941. return Mesh._CAP_ALL;
  13942. },
  13943. enumerable: true,
  13944. configurable: true
  13945. });
  13946. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13947. // Methods
  13948. get: function () {
  13949. return this._LODLevels.length > 0;
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. Mesh.prototype._sortLODLevels = function () {
  13955. this._LODLevels.sort(function (a, b) {
  13956. if (a.distance < b.distance) {
  13957. return 1;
  13958. }
  13959. if (a.distance > b.distance) {
  13960. return -1;
  13961. }
  13962. return 0;
  13963. });
  13964. };
  13965. /**
  13966. * Add a mesh as LOD level triggered at the given distance.
  13967. * @param {number} distance - the distance from the center of the object to show this level
  13968. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13969. * @return {BABYLON.Mesh} this mesh (for chaining)
  13970. */
  13971. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13972. if (mesh && mesh._masterMesh) {
  13973. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13974. return this;
  13975. }
  13976. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13977. this._LODLevels.push(level);
  13978. if (mesh) {
  13979. mesh._masterMesh = this;
  13980. }
  13981. this._sortLODLevels();
  13982. return this;
  13983. };
  13984. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13985. for (var index = 0; index < this._LODLevels.length; index++) {
  13986. var level = this._LODLevels[index];
  13987. if (level.distance === distance) {
  13988. return level.mesh;
  13989. }
  13990. }
  13991. return null;
  13992. };
  13993. /**
  13994. * Remove a mesh from the LOD array
  13995. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13996. * @return {BABYLON.Mesh} this mesh (for chaining)
  13997. */
  13998. Mesh.prototype.removeLODLevel = function (mesh) {
  13999. for (var index = 0; index < this._LODLevels.length; index++) {
  14000. if (this._LODLevels[index].mesh === mesh) {
  14001. this._LODLevels.splice(index, 1);
  14002. if (mesh) {
  14003. mesh._masterMesh = null;
  14004. }
  14005. }
  14006. }
  14007. this._sortLODLevels();
  14008. return this;
  14009. };
  14010. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14011. if (!this._LODLevels || this._LODLevels.length === 0) {
  14012. return this;
  14013. }
  14014. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14015. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14016. if (this.onLODLevelSelection) {
  14017. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14018. }
  14019. return this;
  14020. }
  14021. for (var index = 0; index < this._LODLevels.length; index++) {
  14022. var level = this._LODLevels[index];
  14023. if (level.distance < distanceToCamera) {
  14024. if (level.mesh) {
  14025. level.mesh._preActivate();
  14026. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14027. }
  14028. if (this.onLODLevelSelection) {
  14029. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14030. }
  14031. return level.mesh;
  14032. }
  14033. }
  14034. if (this.onLODLevelSelection) {
  14035. this.onLODLevelSelection(distanceToCamera, this, this);
  14036. }
  14037. return this;
  14038. };
  14039. Object.defineProperty(Mesh.prototype, "geometry", {
  14040. get: function () {
  14041. return this._geometry;
  14042. },
  14043. enumerable: true,
  14044. configurable: true
  14045. });
  14046. Mesh.prototype.getTotalVertices = function () {
  14047. if (!this._geometry) {
  14048. return 0;
  14049. }
  14050. return this._geometry.getTotalVertices();
  14051. };
  14052. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14053. if (!this._geometry) {
  14054. return null;
  14055. }
  14056. return this._geometry.getVerticesData(kind, copyWhenShared);
  14057. };
  14058. Mesh.prototype.getVertexBuffer = function (kind) {
  14059. if (!this._geometry) {
  14060. return undefined;
  14061. }
  14062. return this._geometry.getVertexBuffer(kind);
  14063. };
  14064. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14065. if (!this._geometry) {
  14066. if (this._delayInfo) {
  14067. return this._delayInfo.indexOf(kind) !== -1;
  14068. }
  14069. return false;
  14070. }
  14071. return this._geometry.isVerticesDataPresent(kind);
  14072. };
  14073. Mesh.prototype.getVerticesDataKinds = function () {
  14074. if (!this._geometry) {
  14075. var result = [];
  14076. if (this._delayInfo) {
  14077. for (var kind in this._delayInfo) {
  14078. result.push(kind);
  14079. }
  14080. }
  14081. return result;
  14082. }
  14083. return this._geometry.getVerticesDataKinds();
  14084. };
  14085. Mesh.prototype.getTotalIndices = function () {
  14086. if (!this._geometry) {
  14087. return 0;
  14088. }
  14089. return this._geometry.getTotalIndices();
  14090. };
  14091. Mesh.prototype.getIndices = function (copyWhenShared) {
  14092. if (!this._geometry) {
  14093. return [];
  14094. }
  14095. return this._geometry.getIndices(copyWhenShared);
  14096. };
  14097. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14098. get: function () {
  14099. return this._masterMesh !== null && this._masterMesh !== undefined;
  14100. },
  14101. enumerable: true,
  14102. configurable: true
  14103. });
  14104. Mesh.prototype.isReady = function () {
  14105. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14106. return false;
  14107. }
  14108. return _super.prototype.isReady.call(this);
  14109. };
  14110. Mesh.prototype.isDisposed = function () {
  14111. return this._isDisposed;
  14112. };
  14113. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14114. get: function () {
  14115. return this._sideOrientation;
  14116. },
  14117. set: function (sideO) {
  14118. this._sideOrientation = sideO;
  14119. },
  14120. enumerable: true,
  14121. configurable: true
  14122. });
  14123. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14124. get: function () {
  14125. return this._areNormalsFrozen;
  14126. },
  14127. enumerable: true,
  14128. configurable: true
  14129. });
  14130. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14131. Mesh.prototype.freezeNormals = function () {
  14132. this._areNormalsFrozen = true;
  14133. };
  14134. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14135. Mesh.prototype.unfreezeNormals = function () {
  14136. this._areNormalsFrozen = false;
  14137. };
  14138. // Methods
  14139. Mesh.prototype._preActivate = function () {
  14140. var sceneRenderId = this.getScene().getRenderId();
  14141. if (this._preActivateId === sceneRenderId) {
  14142. return;
  14143. }
  14144. this._preActivateId = sceneRenderId;
  14145. this._visibleInstances = null;
  14146. };
  14147. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14148. if (!this._visibleInstances) {
  14149. this._visibleInstances = {};
  14150. this._visibleInstances.defaultRenderId = renderId;
  14151. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14152. }
  14153. if (!this._visibleInstances[renderId]) {
  14154. this._visibleInstances[renderId] = new Array();
  14155. }
  14156. this._visibleInstances[renderId].push(instance);
  14157. };
  14158. Mesh.prototype.refreshBoundingInfo = function () {
  14159. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14160. if (data) {
  14161. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14162. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14163. }
  14164. if (this.subMeshes) {
  14165. for (var index = 0; index < this.subMeshes.length; index++) {
  14166. this.subMeshes[index].refreshBoundingInfo();
  14167. }
  14168. }
  14169. this._updateBoundingInfo();
  14170. };
  14171. Mesh.prototype._createGlobalSubMesh = function () {
  14172. var totalVertices = this.getTotalVertices();
  14173. if (!totalVertices || !this.getIndices()) {
  14174. return null;
  14175. }
  14176. this.releaseSubMeshes();
  14177. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14178. };
  14179. Mesh.prototype.subdivide = function (count) {
  14180. if (count < 1) {
  14181. return;
  14182. }
  14183. var totalIndices = this.getTotalIndices();
  14184. var subdivisionSize = (totalIndices / count) | 0;
  14185. var offset = 0;
  14186. // Ensure that subdivisionSize is a multiple of 3
  14187. while (subdivisionSize % 3 !== 0) {
  14188. subdivisionSize++;
  14189. }
  14190. this.releaseSubMeshes();
  14191. for (var index = 0; index < count; index++) {
  14192. if (offset >= totalIndices) {
  14193. break;
  14194. }
  14195. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14196. offset += subdivisionSize;
  14197. }
  14198. this.synchronizeInstances();
  14199. };
  14200. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14201. if (!this._geometry) {
  14202. var vertexData = new BABYLON.VertexData();
  14203. vertexData.set(data, kind);
  14204. var scene = this.getScene();
  14205. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14206. }
  14207. else {
  14208. this._geometry.setVerticesData(kind, data, updatable, stride);
  14209. }
  14210. };
  14211. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14212. if (!this._geometry) {
  14213. return;
  14214. }
  14215. if (!makeItUnique) {
  14216. this._geometry.updateVerticesData(kind, data, updateExtends);
  14217. }
  14218. else {
  14219. this.makeGeometryUnique();
  14220. this.updateVerticesData(kind, data, updateExtends, false);
  14221. }
  14222. };
  14223. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14224. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14225. if (!this._geometry) {
  14226. return;
  14227. }
  14228. if (!makeItUnique) {
  14229. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14230. }
  14231. else {
  14232. this.makeGeometryUnique();
  14233. this.updateVerticesDataDirectly(kind, data, offset, false);
  14234. }
  14235. };
  14236. // Mesh positions update function :
  14237. // updates the mesh positions according to the positionFunction returned values.
  14238. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14239. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14240. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14241. if (computeNormals === void 0) { computeNormals = true; }
  14242. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14243. positionFunction(positions);
  14244. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14245. if (computeNormals) {
  14246. var indices = this.getIndices();
  14247. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14248. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14249. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14250. }
  14251. };
  14252. Mesh.prototype.makeGeometryUnique = function () {
  14253. if (!this._geometry) {
  14254. return;
  14255. }
  14256. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14257. geometry.applyToMesh(this);
  14258. };
  14259. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14260. if (!this._geometry) {
  14261. var vertexData = new BABYLON.VertexData();
  14262. vertexData.indices = indices;
  14263. var scene = this.getScene();
  14264. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14265. }
  14266. else {
  14267. this._geometry.setIndices(indices, totalVertices);
  14268. }
  14269. };
  14270. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14271. var engine = this.getScene().getEngine();
  14272. // Wireframe
  14273. var indexToBind;
  14274. switch (fillMode) {
  14275. case BABYLON.Material.PointFillMode:
  14276. indexToBind = null;
  14277. break;
  14278. case BABYLON.Material.WireFrameFillMode:
  14279. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14280. break;
  14281. default:
  14282. case BABYLON.Material.TriangleFillMode:
  14283. indexToBind = this._geometry.getIndexBuffer();
  14284. break;
  14285. }
  14286. // VBOs
  14287. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14288. };
  14289. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14290. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14291. return;
  14292. }
  14293. var engine = this.getScene().getEngine();
  14294. // Draw order
  14295. switch (fillMode) {
  14296. case BABYLON.Material.PointFillMode:
  14297. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14298. break;
  14299. case BABYLON.Material.WireFrameFillMode:
  14300. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14301. break;
  14302. default:
  14303. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14304. }
  14305. };
  14306. Mesh.prototype.registerBeforeRender = function (func) {
  14307. this._onBeforeRenderCallbacks.push(func);
  14308. };
  14309. Mesh.prototype.unregisterBeforeRender = function (func) {
  14310. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14311. if (index > -1) {
  14312. this._onBeforeRenderCallbacks.splice(index, 1);
  14313. }
  14314. };
  14315. Mesh.prototype.registerAfterRender = function (func) {
  14316. this._onAfterRenderCallbacks.push(func);
  14317. };
  14318. Mesh.prototype.unregisterAfterRender = function (func) {
  14319. var index = this._onAfterRenderCallbacks.indexOf(func);
  14320. if (index > -1) {
  14321. this._onAfterRenderCallbacks.splice(index, 1);
  14322. }
  14323. };
  14324. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14325. var scene = this.getScene();
  14326. this._batchCache.mustReturn = false;
  14327. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14328. this._batchCache.visibleInstances[subMeshId] = null;
  14329. if (this._visibleInstances) {
  14330. var currentRenderId = scene.getRenderId();
  14331. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14332. var selfRenderId = this._renderId;
  14333. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14334. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14335. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14336. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14337. }
  14338. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14339. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14340. this._batchCache.mustReturn = true;
  14341. return this._batchCache;
  14342. }
  14343. if (currentRenderId !== selfRenderId) {
  14344. this._batchCache.renderSelf[subMeshId] = false;
  14345. }
  14346. }
  14347. this._renderIdForInstances[subMeshId] = currentRenderId;
  14348. }
  14349. return this._batchCache;
  14350. };
  14351. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14352. var visibleInstances = batch.visibleInstances[subMesh._id];
  14353. var matricesCount = visibleInstances.length + 1;
  14354. var bufferSize = matricesCount * 16 * 4;
  14355. while (this._instancesBufferSize < bufferSize) {
  14356. this._instancesBufferSize *= 2;
  14357. }
  14358. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14359. if (this._worldMatricesInstancesBuffer) {
  14360. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14361. }
  14362. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14363. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14364. }
  14365. var offset = 0;
  14366. var instancesCount = 0;
  14367. var world = this.getWorldMatrix();
  14368. if (batch.renderSelf[subMesh._id]) {
  14369. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14370. offset += 16;
  14371. instancesCount++;
  14372. }
  14373. if (visibleInstances) {
  14374. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14375. var instance = visibleInstances[instanceIndex];
  14376. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14377. offset += 16;
  14378. instancesCount++;
  14379. }
  14380. }
  14381. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14382. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14383. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14384. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14385. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14386. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14387. this._draw(subMesh, fillMode, instancesCount);
  14388. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14389. };
  14390. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14391. var scene = this.getScene();
  14392. var engine = scene.getEngine();
  14393. if (hardwareInstancedRendering) {
  14394. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14395. }
  14396. else {
  14397. if (batch.renderSelf[subMesh._id]) {
  14398. // Draw
  14399. if (onBeforeDraw) {
  14400. onBeforeDraw(false, this.getWorldMatrix());
  14401. }
  14402. this._draw(subMesh, fillMode);
  14403. }
  14404. if (batch.visibleInstances[subMesh._id]) {
  14405. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14406. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14407. // World
  14408. var world = instance.getWorldMatrix();
  14409. if (onBeforeDraw) {
  14410. onBeforeDraw(true, world);
  14411. }
  14412. // Draw
  14413. this._draw(subMesh, fillMode);
  14414. }
  14415. }
  14416. }
  14417. };
  14418. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14419. var scene = this.getScene();
  14420. // Managing instances
  14421. var batch = this._getInstancesRenderList(subMesh._id);
  14422. if (batch.mustReturn) {
  14423. return;
  14424. }
  14425. // Checking geometry state
  14426. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14427. return;
  14428. }
  14429. var callbackIndex;
  14430. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14431. this._onBeforeRenderCallbacks[callbackIndex](this);
  14432. }
  14433. var engine = scene.getEngine();
  14434. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14435. // Material
  14436. var effectiveMaterial = subMesh.getMaterial();
  14437. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14438. return;
  14439. }
  14440. // Outline - step 1
  14441. var savedDepthWrite = engine.getDepthWrite();
  14442. if (this.renderOutline) {
  14443. engine.setDepthWrite(false);
  14444. scene.getOutlineRenderer().render(subMesh, batch);
  14445. engine.setDepthWrite(savedDepthWrite);
  14446. }
  14447. effectiveMaterial._preBind();
  14448. var effect = effectiveMaterial.getEffect();
  14449. // Bind
  14450. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14451. this._bind(subMesh, effect, fillMode);
  14452. var world = this.getWorldMatrix();
  14453. effectiveMaterial.bind(world, this);
  14454. // Alpha mode
  14455. if (enableAlphaMode) {
  14456. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14457. }
  14458. // Draw
  14459. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14460. if (isInstance) {
  14461. effectiveMaterial.bindOnlyWorldMatrix(world);
  14462. }
  14463. });
  14464. // Unbind
  14465. effectiveMaterial.unbind();
  14466. // Outline - step 2
  14467. if (this.renderOutline && savedDepthWrite) {
  14468. engine.setDepthWrite(true);
  14469. engine.setColorWrite(false);
  14470. scene.getOutlineRenderer().render(subMesh, batch);
  14471. engine.setColorWrite(true);
  14472. }
  14473. // Overlay
  14474. if (this.renderOverlay) {
  14475. var currentMode = engine.getAlphaMode();
  14476. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14477. scene.getOutlineRenderer().render(subMesh, batch, true);
  14478. engine.setAlphaMode(currentMode);
  14479. }
  14480. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14481. this._onAfterRenderCallbacks[callbackIndex](this);
  14482. }
  14483. };
  14484. Mesh.prototype.getEmittedParticleSystems = function () {
  14485. var results = new Array();
  14486. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14487. var particleSystem = this.getScene().particleSystems[index];
  14488. if (particleSystem.emitter === this) {
  14489. results.push(particleSystem);
  14490. }
  14491. }
  14492. return results;
  14493. };
  14494. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14495. var results = new Array();
  14496. var descendants = this.getDescendants();
  14497. descendants.push(this);
  14498. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14499. var particleSystem = this.getScene().particleSystems[index];
  14500. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14501. results.push(particleSystem);
  14502. }
  14503. }
  14504. return results;
  14505. };
  14506. Mesh.prototype.getChildren = function () {
  14507. var results = [];
  14508. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14509. var mesh = this.getScene().meshes[index];
  14510. if (mesh.parent === this) {
  14511. results.push(mesh);
  14512. }
  14513. }
  14514. return results;
  14515. };
  14516. Mesh.prototype._checkDelayState = function () {
  14517. var _this = this;
  14518. var that = this;
  14519. var scene = this.getScene();
  14520. if (this._geometry) {
  14521. this._geometry.load(scene);
  14522. }
  14523. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14524. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14525. scene._addPendingData(that);
  14526. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14527. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14528. if (data instanceof ArrayBuffer) {
  14529. _this._delayLoadingFunction(data, _this);
  14530. }
  14531. else {
  14532. _this._delayLoadingFunction(JSON.parse(data), _this);
  14533. }
  14534. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14535. scene._removePendingData(_this);
  14536. }, function () { }, scene.database, getBinaryData);
  14537. }
  14538. };
  14539. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14540. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14541. return false;
  14542. }
  14543. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14544. return false;
  14545. }
  14546. this._checkDelayState();
  14547. return true;
  14548. };
  14549. Mesh.prototype.setMaterialByID = function (id) {
  14550. var materials = this.getScene().materials;
  14551. var index;
  14552. for (index = 0; index < materials.length; index++) {
  14553. if (materials[index].id === id) {
  14554. this.material = materials[index];
  14555. return;
  14556. }
  14557. }
  14558. // Multi
  14559. var multiMaterials = this.getScene().multiMaterials;
  14560. for (index = 0; index < multiMaterials.length; index++) {
  14561. if (multiMaterials[index].id === id) {
  14562. this.material = multiMaterials[index];
  14563. return;
  14564. }
  14565. }
  14566. };
  14567. Mesh.prototype.getAnimatables = function () {
  14568. var results = [];
  14569. if (this.material) {
  14570. results.push(this.material);
  14571. }
  14572. if (this.skeleton) {
  14573. results.push(this.skeleton);
  14574. }
  14575. return results;
  14576. };
  14577. // Geometry
  14578. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14579. // Position
  14580. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14581. return;
  14582. }
  14583. this._resetPointsArrayCache();
  14584. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14585. var temp = [];
  14586. var index;
  14587. for (index = 0; index < data.length; index += 3) {
  14588. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14589. }
  14590. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14591. // Normals
  14592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14593. return;
  14594. }
  14595. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14596. temp = [];
  14597. for (index = 0; index < data.length; index += 3) {
  14598. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14599. }
  14600. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14601. // flip faces?
  14602. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14603. this.flipFaces();
  14604. }
  14605. };
  14606. // Will apply current transform to mesh and reset world matrix
  14607. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14608. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14609. this.scaling.copyFromFloats(1, 1, 1);
  14610. this.position.copyFromFloats(0, 0, 0);
  14611. this.rotation.copyFromFloats(0, 0, 0);
  14612. //only if quaternion is already set
  14613. if (this.rotationQuaternion) {
  14614. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14615. }
  14616. this._worldMatrix = BABYLON.Matrix.Identity();
  14617. };
  14618. // Cache
  14619. Mesh.prototype._resetPointsArrayCache = function () {
  14620. this._positions = null;
  14621. };
  14622. Mesh.prototype._generatePointsArray = function () {
  14623. if (this._positions)
  14624. return true;
  14625. this._positions = [];
  14626. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14627. if (!data) {
  14628. return false;
  14629. }
  14630. for (var index = 0; index < data.length; index += 3) {
  14631. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14632. }
  14633. return true;
  14634. };
  14635. // Clone
  14636. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14637. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14638. };
  14639. // Dispose
  14640. Mesh.prototype.dispose = function (doNotRecurse) {
  14641. if (this._geometry) {
  14642. this._geometry.releaseForMesh(this, true);
  14643. }
  14644. // Instances
  14645. if (this._worldMatricesInstancesBuffer) {
  14646. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14647. this._worldMatricesInstancesBuffer = null;
  14648. }
  14649. while (this.instances.length) {
  14650. this.instances[0].dispose();
  14651. }
  14652. _super.prototype.dispose.call(this, doNotRecurse);
  14653. };
  14654. // Geometric tools
  14655. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14656. var _this = this;
  14657. var scene = this.getScene();
  14658. var onload = function (img) {
  14659. // Getting height map data
  14660. var canvas = document.createElement("canvas");
  14661. var context = canvas.getContext("2d");
  14662. var heightMapWidth = img.width;
  14663. var heightMapHeight = img.height;
  14664. canvas.width = heightMapWidth;
  14665. canvas.height = heightMapHeight;
  14666. context.drawImage(img, 0, 0);
  14667. // Create VertexData from map data
  14668. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14669. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14670. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14671. //execute success callback, if set
  14672. if (onSuccess) {
  14673. onSuccess(_this);
  14674. }
  14675. };
  14676. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14677. };
  14678. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14679. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14680. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14681. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14682. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14683. return;
  14684. }
  14685. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14686. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14687. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14688. var position = BABYLON.Vector3.Zero();
  14689. var normal = BABYLON.Vector3.Zero();
  14690. var uv = BABYLON.Vector2.Zero();
  14691. for (var index = 0; index < positions.length; index += 3) {
  14692. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14693. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14694. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14695. // Compute height
  14696. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14697. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14698. var pos = (u + v * heightMapWidth) * 4;
  14699. var r = buffer[pos] / 255.0;
  14700. var g = buffer[pos + 1] / 255.0;
  14701. var b = buffer[pos + 2] / 255.0;
  14702. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14703. normal.normalize();
  14704. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14705. position = position.add(normal);
  14706. position.toArray(positions, index);
  14707. }
  14708. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14709. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14710. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14711. };
  14712. Mesh.prototype.convertToFlatShadedMesh = function () {
  14713. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14714. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14715. var kinds = this.getVerticesDataKinds();
  14716. var vbs = [];
  14717. var data = [];
  14718. var newdata = [];
  14719. var updatableNormals = false;
  14720. var kindIndex;
  14721. var kind;
  14722. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14723. kind = kinds[kindIndex];
  14724. var vertexBuffer = this.getVertexBuffer(kind);
  14725. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14726. updatableNormals = vertexBuffer.isUpdatable();
  14727. kinds.splice(kindIndex, 1);
  14728. kindIndex--;
  14729. continue;
  14730. }
  14731. vbs[kind] = vertexBuffer;
  14732. data[kind] = vbs[kind].getData();
  14733. newdata[kind] = [];
  14734. }
  14735. // Save previous submeshes
  14736. var previousSubmeshes = this.subMeshes.slice(0);
  14737. var indices = this.getIndices();
  14738. var totalIndices = this.getTotalIndices();
  14739. // Generating unique vertices per face
  14740. var index;
  14741. for (index = 0; index < totalIndices; index++) {
  14742. var vertexIndex = indices[index];
  14743. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14744. kind = kinds[kindIndex];
  14745. var stride = vbs[kind].getStrideSize();
  14746. for (var offset = 0; offset < stride; offset++) {
  14747. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14748. }
  14749. }
  14750. }
  14751. // Updating faces & normal
  14752. var normals = [];
  14753. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14754. for (index = 0; index < totalIndices; index += 3) {
  14755. indices[index] = index;
  14756. indices[index + 1] = index + 1;
  14757. indices[index + 2] = index + 2;
  14758. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14759. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14760. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14761. var p1p2 = p1.subtract(p2);
  14762. var p3p2 = p3.subtract(p2);
  14763. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14764. // Store same normals for every vertex
  14765. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14766. normals.push(normal.x);
  14767. normals.push(normal.y);
  14768. normals.push(normal.z);
  14769. }
  14770. }
  14771. this.setIndices(indices);
  14772. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14773. // Updating vertex buffers
  14774. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14775. kind = kinds[kindIndex];
  14776. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14777. }
  14778. // Updating submeshes
  14779. this.releaseSubMeshes();
  14780. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14781. var previousOne = previousSubmeshes[submeshIndex];
  14782. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14783. }
  14784. this.synchronizeInstances();
  14785. };
  14786. // will inverse faces orientations, and invert normals too if specified
  14787. Mesh.prototype.flipFaces = function (flipNormals) {
  14788. if (flipNormals === void 0) { flipNormals = false; }
  14789. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14790. var i;
  14791. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14792. for (i = 0; i < vertex_data.normals.length; i++) {
  14793. vertex_data.normals[i] *= -1;
  14794. }
  14795. }
  14796. var temp;
  14797. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14798. // reassign indices
  14799. temp = vertex_data.indices[i + 1];
  14800. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14801. vertex_data.indices[i + 2] = temp;
  14802. }
  14803. vertex_data.applyToMesh(this);
  14804. };
  14805. // Instances
  14806. Mesh.prototype.createInstance = function (name) {
  14807. return new BABYLON.InstancedMesh(name, this);
  14808. };
  14809. Mesh.prototype.synchronizeInstances = function () {
  14810. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14811. var instance = this.instances[instanceIndex];
  14812. instance._syncSubMeshes();
  14813. }
  14814. };
  14815. /**
  14816. * Simplify the mesh according to the given array of settings.
  14817. * Function will return immediately and will simplify async.
  14818. * @param settings a collection of simplification settings.
  14819. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14820. * @param type the type of simplification to run.
  14821. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14822. */
  14823. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14824. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14825. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14826. this.getScene().simplificationQueue.addTask({
  14827. settings: settings,
  14828. parallelProcessing: parallelProcessing,
  14829. mesh: this,
  14830. simplificationType: simplificationType,
  14831. successCallback: successCallback
  14832. });
  14833. };
  14834. /**
  14835. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14836. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14837. * This should be used together with the simplification to avoid disappearing triangles.
  14838. * @param successCallback an optional success callback to be called after the optimization finished.
  14839. */
  14840. Mesh.prototype.optimizeIndices = function (successCallback) {
  14841. var _this = this;
  14842. var indices = this.getIndices();
  14843. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14844. var vectorPositions = [];
  14845. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14846. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14847. }
  14848. var dupes = [];
  14849. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14850. var realPos = vectorPositions.length - 1 - iteration;
  14851. var testedPosition = vectorPositions[realPos];
  14852. for (var j = 0; j < realPos; ++j) {
  14853. var againstPosition = vectorPositions[j];
  14854. if (testedPosition.equals(againstPosition)) {
  14855. dupes[realPos] = j;
  14856. break;
  14857. }
  14858. }
  14859. }, function () {
  14860. for (var i = 0; i < indices.length; ++i) {
  14861. indices[i] = dupes[indices[i]] || indices[i];
  14862. }
  14863. //indices are now reordered
  14864. var originalSubMeshes = _this.subMeshes.slice(0);
  14865. _this.setIndices(indices);
  14866. _this.subMeshes = originalSubMeshes;
  14867. if (successCallback) {
  14868. successCallback(_this);
  14869. }
  14870. });
  14871. };
  14872. // Statics
  14873. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14874. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14875. pathArray: pathArray,
  14876. closeArray: closeArray,
  14877. closePath: closePath,
  14878. offset: offset,
  14879. updatable: updatable,
  14880. sideOrientation: sideOrientation,
  14881. instance: instance
  14882. }, scene);
  14883. };
  14884. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14885. var options = {
  14886. radius: radius,
  14887. tessellation: tessellation,
  14888. sideOrientation: sideOrientation,
  14889. updatable: updatable
  14890. };
  14891. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14892. };
  14893. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14894. var options = {
  14895. size: size,
  14896. sideOrientation: sideOrientation,
  14897. updatable: updatable
  14898. };
  14899. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14900. };
  14901. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14902. var options = {
  14903. segments: segments,
  14904. diameterX: diameter,
  14905. diameterY: diameter,
  14906. diameterZ: diameter,
  14907. sideOrientation: sideOrientation,
  14908. updatable: updatable
  14909. };
  14910. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14911. };
  14912. // Cylinder and cone
  14913. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14914. var options = {
  14915. height: height,
  14916. diameterTop: diameterTop,
  14917. diameterBottom: diameterBottom,
  14918. tessellation: tessellation,
  14919. subdivisions: subdivisions,
  14920. sideOrientation: sideOrientation,
  14921. updatable: updatable
  14922. };
  14923. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14924. };
  14925. // Torus (Code from SharpDX.org)
  14926. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14927. var options = {
  14928. diameter: diameter,
  14929. thickness: thickness,
  14930. tessellation: tessellation,
  14931. sideOrientation: sideOrientation,
  14932. updatable: updatable
  14933. };
  14934. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14935. };
  14936. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14937. var options = {
  14938. radius: radius,
  14939. tube: tube,
  14940. radialSegments: radialSegments,
  14941. tubularSegments: tubularSegments,
  14942. p: p,
  14943. q: q,
  14944. sideOrientation: sideOrientation,
  14945. updatable: updatable
  14946. };
  14947. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14948. };
  14949. // Lines
  14950. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14951. var options = {
  14952. points: points,
  14953. updatable: updatable,
  14954. instance: instance
  14955. };
  14956. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14957. };
  14958. // Dashed Lines
  14959. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14960. var options = {
  14961. points: points,
  14962. dashSize: dashSize,
  14963. gapSize: gapSize,
  14964. dashNb: dashNb,
  14965. updatable: updatable
  14966. };
  14967. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14968. };
  14969. // Extrusion
  14970. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14971. var options = {
  14972. shape: shape,
  14973. path: path,
  14974. scale: scale,
  14975. rotation: rotation,
  14976. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14977. sideOrientation: sideOrientation,
  14978. instance: instance,
  14979. updatable: updatable
  14980. };
  14981. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14982. };
  14983. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14984. var options = {
  14985. shape: shape,
  14986. path: path,
  14987. scaleFunction: scaleFunction,
  14988. rotationFunction: rotationFunction,
  14989. ribbonCloseArray: ribbonCloseArray,
  14990. ribbonClosePath: ribbonClosePath,
  14991. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14992. sideOrientation: sideOrientation,
  14993. instance: instance,
  14994. updatable: updatable
  14995. };
  14996. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14997. };
  14998. // Lathe
  14999. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15000. var options = {
  15001. shape: shape,
  15002. radius: radius,
  15003. tesselation: tessellation,
  15004. sideOrientation: sideOrientation,
  15005. updatable: updatable
  15006. };
  15007. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15008. };
  15009. // Plane & ground
  15010. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15011. var options = {
  15012. size: size,
  15013. width: size,
  15014. height: size,
  15015. sideOrientation: sideOrientation,
  15016. updatable: updatable
  15017. };
  15018. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15019. };
  15020. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15021. var options = {
  15022. width: width,
  15023. height: height,
  15024. subdivisions: subdivisions,
  15025. updatable: updatable
  15026. };
  15027. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15028. };
  15029. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15030. var options = {
  15031. xmin: xmin,
  15032. zmin: zmin,
  15033. xmax: xmax,
  15034. zmax: zmax,
  15035. subdivisions: subdivisions,
  15036. precision: precision,
  15037. updatable: updatable
  15038. };
  15039. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15040. };
  15041. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15042. var options = {
  15043. width: width,
  15044. height: height,
  15045. subdivisions: subdivisions,
  15046. minHeight: minHeight,
  15047. maxHeight: maxHeight,
  15048. updatable: updatable,
  15049. onReady: onReady
  15050. };
  15051. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15052. };
  15053. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15054. var options = {
  15055. path: path,
  15056. radius: radius,
  15057. tessellation: tessellation,
  15058. radiusFunction: radiusFunction,
  15059. arc: 1,
  15060. cap: cap,
  15061. updatable: updatable,
  15062. sideOrientation: sideOrientation,
  15063. instance: instance
  15064. };
  15065. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15066. };
  15067. Mesh.CreatePolyhedron = function (name, options, scene) {
  15068. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15069. };
  15070. Mesh.CreateIcoSphere = function (name, options, scene) {
  15071. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15072. };
  15073. // Decals
  15074. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15075. var options = {
  15076. position: position,
  15077. normal: normal,
  15078. size: size,
  15079. angle: angle
  15080. };
  15081. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15082. };
  15083. // Skeletons
  15084. /**
  15085. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15086. */
  15087. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15088. var source;
  15089. if (!this._sourcePositions) {
  15090. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15091. this._sourcePositions = new Float32Array(source);
  15092. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15093. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15094. }
  15095. }
  15096. return this._sourcePositions;
  15097. };
  15098. /**
  15099. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15100. */
  15101. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15102. var source;
  15103. if (!this._sourceNormals) {
  15104. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15105. this._sourceNormals = new Float32Array(source);
  15106. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15107. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15108. }
  15109. }
  15110. return this._sourceNormals;
  15111. };
  15112. /**
  15113. * Update the vertex buffers by applying transformation from the bones
  15114. * @param {skeleton} skeleton to apply
  15115. */
  15116. Mesh.prototype.applySkeleton = function (skeleton) {
  15117. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15118. return this;
  15119. }
  15120. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15121. return this;
  15122. }
  15123. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15124. return this;
  15125. }
  15126. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15127. return this;
  15128. }
  15129. if (!this._sourcePositions) {
  15130. this.setPositionsForCPUSkinning();
  15131. }
  15132. if (!this._sourceNormals) {
  15133. this.setNormalsForCPUSkinning();
  15134. }
  15135. // positionsData checks for not being Float32Array will only pass at most once
  15136. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15137. if (!(positionsData instanceof Float32Array)) {
  15138. positionsData = new Float32Array(positionsData);
  15139. }
  15140. // normalsData checks for not being Float32Array will only pass at most once
  15141. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15142. if (!(normalsData instanceof Float32Array)) {
  15143. normalsData = new Float32Array(normalsData);
  15144. }
  15145. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15146. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15147. var needExtras = this.numBoneInfluencers > 4;
  15148. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15149. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15150. var skeletonMatrices = skeleton.getTransformMatrices();
  15151. var tempVector3 = BABYLON.Vector3.Zero();
  15152. var finalMatrix = new BABYLON.Matrix();
  15153. var tempMatrix = new BABYLON.Matrix();
  15154. var matWeightIdx = 0;
  15155. var inf;
  15156. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15157. for (inf = 0; inf < 4; inf++) {
  15158. var weight = matricesWeightsData[matWeightIdx + inf];
  15159. if (weight > 0) {
  15160. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15161. finalMatrix.addToSelf(tempMatrix);
  15162. }
  15163. else
  15164. break;
  15165. }
  15166. if (needExtras) {
  15167. for (inf = 0; inf < 4; inf++) {
  15168. var weight = matricesWeightsExtraData[matWeightIdx + inf];
  15169. if (weight > 0) {
  15170. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15171. finalMatrix.addToSelf(tempMatrix);
  15172. }
  15173. else
  15174. break;
  15175. }
  15176. }
  15177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15178. tempVector3.toArray(positionsData, index);
  15179. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15180. tempVector3.toArray(normalsData, index);
  15181. finalMatrix.reset();
  15182. }
  15183. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15184. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15185. return this;
  15186. };
  15187. // Tools
  15188. Mesh.MinMax = function (meshes) {
  15189. var minVector = null;
  15190. var maxVector = null;
  15191. for (var i in meshes) {
  15192. var mesh = meshes[i];
  15193. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15194. if (!minVector) {
  15195. minVector = boundingBox.minimumWorld;
  15196. maxVector = boundingBox.maximumWorld;
  15197. continue;
  15198. }
  15199. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15200. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15201. }
  15202. return {
  15203. min: minVector,
  15204. max: maxVector
  15205. };
  15206. };
  15207. Mesh.Center = function (meshesOrMinMaxVector) {
  15208. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15209. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15210. };
  15211. /**
  15212. * Merge the array of meshes into a single mesh for performance reasons.
  15213. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15214. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15215. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15216. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15217. */
  15218. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15219. if (disposeSource === void 0) { disposeSource = true; }
  15220. var index;
  15221. if (!allow32BitsIndices) {
  15222. var totalVertices = 0;
  15223. // Counting vertices
  15224. for (index = 0; index < meshes.length; index++) {
  15225. if (meshes[index]) {
  15226. totalVertices += meshes[index].getTotalVertices();
  15227. if (totalVertices > 65536) {
  15228. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15229. return null;
  15230. }
  15231. }
  15232. }
  15233. }
  15234. // Merge
  15235. var vertexData;
  15236. var otherVertexData;
  15237. var source;
  15238. for (index = 0; index < meshes.length; index++) {
  15239. if (meshes[index]) {
  15240. meshes[index].computeWorldMatrix(true);
  15241. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15242. otherVertexData.transform(meshes[index].getWorldMatrix());
  15243. if (vertexData) {
  15244. vertexData.merge(otherVertexData);
  15245. }
  15246. else {
  15247. vertexData = otherVertexData;
  15248. source = meshes[index];
  15249. }
  15250. }
  15251. }
  15252. if (!meshSubclass) {
  15253. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15254. }
  15255. vertexData.applyToMesh(meshSubclass);
  15256. // Setting properties
  15257. meshSubclass.material = source.material;
  15258. meshSubclass.checkCollisions = source.checkCollisions;
  15259. // Cleaning
  15260. if (disposeSource) {
  15261. for (index = 0; index < meshes.length; index++) {
  15262. if (meshes[index]) {
  15263. meshes[index].dispose();
  15264. }
  15265. }
  15266. }
  15267. return meshSubclass;
  15268. };
  15269. // Consts
  15270. Mesh._FRONTSIDE = 0;
  15271. Mesh._BACKSIDE = 1;
  15272. Mesh._DOUBLESIDE = 2;
  15273. Mesh._DEFAULTSIDE = 0;
  15274. Mesh._NO_CAP = 0;
  15275. Mesh._CAP_START = 1;
  15276. Mesh._CAP_END = 2;
  15277. Mesh._CAP_ALL = 3;
  15278. return Mesh;
  15279. })(BABYLON.AbstractMesh);
  15280. BABYLON.Mesh = Mesh;
  15281. })(BABYLON || (BABYLON = {}));
  15282. var BABYLON;
  15283. (function (BABYLON) {
  15284. var SubMesh = (function () {
  15285. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15286. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15287. this.materialIndex = materialIndex;
  15288. this.verticesStart = verticesStart;
  15289. this.verticesCount = verticesCount;
  15290. this.indexStart = indexStart;
  15291. this.indexCount = indexCount;
  15292. this._renderId = 0;
  15293. this._mesh = mesh;
  15294. this._renderingMesh = renderingMesh || mesh;
  15295. mesh.subMeshes.push(this);
  15296. this._trianglePlanes = [];
  15297. this._id = mesh.subMeshes.length - 1;
  15298. if (createBoundingBox) {
  15299. this.refreshBoundingInfo();
  15300. mesh.computeWorldMatrix(true);
  15301. }
  15302. }
  15303. SubMesh.prototype.getBoundingInfo = function () {
  15304. return this._boundingInfo;
  15305. };
  15306. SubMesh.prototype.getMesh = function () {
  15307. return this._mesh;
  15308. };
  15309. SubMesh.prototype.getRenderingMesh = function () {
  15310. return this._renderingMesh;
  15311. };
  15312. SubMesh.prototype.getMaterial = function () {
  15313. var rootMaterial = this._renderingMesh.material;
  15314. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15315. var multiMaterial = rootMaterial;
  15316. return multiMaterial.getSubMaterial(this.materialIndex);
  15317. }
  15318. if (!rootMaterial) {
  15319. return this._mesh.getScene().defaultMaterial;
  15320. }
  15321. return rootMaterial;
  15322. };
  15323. // Methods
  15324. SubMesh.prototype.refreshBoundingInfo = function () {
  15325. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15326. if (!data) {
  15327. this._boundingInfo = this._mesh._boundingInfo;
  15328. return;
  15329. }
  15330. var indices = this._renderingMesh.getIndices();
  15331. var extend;
  15332. //is this the only submesh?
  15333. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15334. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15335. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15336. }
  15337. else {
  15338. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15339. }
  15340. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15341. };
  15342. SubMesh.prototype._checkCollision = function (collider) {
  15343. return this._boundingInfo._checkCollision(collider);
  15344. };
  15345. SubMesh.prototype.updateBoundingInfo = function (world) {
  15346. if (!this._boundingInfo) {
  15347. this.refreshBoundingInfo();
  15348. }
  15349. this._boundingInfo._update(world);
  15350. };
  15351. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15352. return this._boundingInfo.isInFrustum(frustumPlanes);
  15353. };
  15354. SubMesh.prototype.render = function (enableAlphaMode) {
  15355. this._renderingMesh.render(this, enableAlphaMode);
  15356. };
  15357. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15358. if (!this._linesIndexBuffer) {
  15359. var linesIndices = [];
  15360. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15361. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15362. }
  15363. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15364. this.linesIndexCount = linesIndices.length;
  15365. }
  15366. return this._linesIndexBuffer;
  15367. };
  15368. SubMesh.prototype.canIntersects = function (ray) {
  15369. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15370. };
  15371. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15372. var intersectInfo = null;
  15373. // Triangles test
  15374. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15375. var p0 = positions[indices[index]];
  15376. var p1 = positions[indices[index + 1]];
  15377. var p2 = positions[indices[index + 2]];
  15378. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15379. if (currentIntersectInfo) {
  15380. if (currentIntersectInfo.distance < 0) {
  15381. continue;
  15382. }
  15383. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15384. intersectInfo = currentIntersectInfo;
  15385. intersectInfo.faceId = index / 3;
  15386. if (fastCheck) {
  15387. break;
  15388. }
  15389. }
  15390. }
  15391. }
  15392. return intersectInfo;
  15393. };
  15394. // Clone
  15395. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15396. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15397. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15398. return result;
  15399. };
  15400. // Dispose
  15401. SubMesh.prototype.dispose = function () {
  15402. if (this._linesIndexBuffer) {
  15403. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15404. this._linesIndexBuffer = null;
  15405. }
  15406. // Remove from mesh
  15407. var index = this._mesh.subMeshes.indexOf(this);
  15408. this._mesh.subMeshes.splice(index, 1);
  15409. };
  15410. // Statics
  15411. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15412. var minVertexIndex = Number.MAX_VALUE;
  15413. var maxVertexIndex = -Number.MAX_VALUE;
  15414. renderingMesh = renderingMesh || mesh;
  15415. var indices = renderingMesh.getIndices();
  15416. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15417. var vertexIndex = indices[index];
  15418. if (vertexIndex < minVertexIndex)
  15419. minVertexIndex = vertexIndex;
  15420. if (vertexIndex > maxVertexIndex)
  15421. maxVertexIndex = vertexIndex;
  15422. }
  15423. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15424. };
  15425. return SubMesh;
  15426. })();
  15427. BABYLON.SubMesh = SubMesh;
  15428. })(BABYLON || (BABYLON = {}));
  15429. var BABYLON;
  15430. (function (BABYLON) {
  15431. var MeshBuilder = (function () {
  15432. function MeshBuilder() {
  15433. }
  15434. MeshBuilder.CreateBox = function (name, options, scene) {
  15435. var box = new BABYLON.Mesh(name, scene);
  15436. var vertexData = BABYLON.VertexData.CreateBox(options);
  15437. vertexData.applyToMesh(box, options.updatable);
  15438. return box;
  15439. };
  15440. MeshBuilder.CreateSphere = function (name, options, scene) {
  15441. var sphere = new BABYLON.Mesh(name, scene);
  15442. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15443. vertexData.applyToMesh(sphere, options.updatable);
  15444. return sphere;
  15445. };
  15446. MeshBuilder.CreateDisc = function (name, options, scene) {
  15447. var disc = new BABYLON.Mesh(name, scene);
  15448. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15449. vertexData.applyToMesh(disc, options.updatable);
  15450. return disc;
  15451. };
  15452. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15453. var sphere = new BABYLON.Mesh(name, scene);
  15454. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15455. vertexData.applyToMesh(sphere, options.updatable);
  15456. return sphere;
  15457. };
  15458. ;
  15459. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15460. var pathArray = options.pathArray;
  15461. var closeArray = options.closeArray;
  15462. var closePath = options.closePath;
  15463. var offset = options.offset;
  15464. var sideOrientation = options.sideOrientation;
  15465. var instance = options.instance;
  15466. var updatable = options.updatable;
  15467. if (instance) {
  15468. // positionFunction : ribbon case
  15469. // only pathArray and sideOrientation parameters are taken into account for positions update
  15470. var positionFunction = function (positions) {
  15471. var minlg = pathArray[0].length;
  15472. var i = 0;
  15473. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15474. for (var si = 1; si <= ns; si++) {
  15475. for (var p = 0; p < pathArray.length; p++) {
  15476. var path = pathArray[p];
  15477. var l = path.length;
  15478. minlg = (minlg < l) ? minlg : l;
  15479. var j = 0;
  15480. while (j < minlg) {
  15481. positions[i] = path[j].x;
  15482. positions[i + 1] = path[j].y;
  15483. positions[i + 2] = path[j].z;
  15484. j++;
  15485. i += 3;
  15486. }
  15487. if (instance._closePath) {
  15488. positions[i] = path[0].x;
  15489. positions[i + 1] = path[0].y;
  15490. positions[i + 2] = path[0].z;
  15491. i += 3;
  15492. }
  15493. }
  15494. }
  15495. };
  15496. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15497. positionFunction(positions);
  15498. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15499. if (!(instance.areNormalsFrozen)) {
  15500. var indices = instance.getIndices();
  15501. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15502. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15503. if (instance._closePath) {
  15504. var indexFirst = 0;
  15505. var indexLast = 0;
  15506. for (var p = 0; p < pathArray.length; p++) {
  15507. indexFirst = instance._idx[p] * 3;
  15508. if (p + 1 < pathArray.length) {
  15509. indexLast = (instance._idx[p + 1] - 1) * 3;
  15510. }
  15511. else {
  15512. indexLast = normals.length - 3;
  15513. }
  15514. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15515. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15516. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15517. normals[indexLast] = normals[indexFirst];
  15518. normals[indexLast + 1] = normals[indexFirst + 1];
  15519. normals[indexLast + 2] = normals[indexFirst + 2];
  15520. }
  15521. }
  15522. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15523. }
  15524. return instance;
  15525. }
  15526. else {
  15527. var ribbon = new BABYLON.Mesh(name, scene);
  15528. ribbon.sideOrientation = sideOrientation;
  15529. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15530. if (closePath) {
  15531. ribbon._idx = vertexData._idx;
  15532. }
  15533. ribbon._closePath = closePath;
  15534. ribbon._closeArray = closeArray;
  15535. vertexData.applyToMesh(ribbon, updatable);
  15536. return ribbon;
  15537. }
  15538. };
  15539. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15540. var cylinder = new BABYLON.Mesh(name, scene);
  15541. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15542. vertexData.applyToMesh(cylinder, options.updatable);
  15543. return cylinder;
  15544. };
  15545. MeshBuilder.CreateTorus = function (name, options, scene) {
  15546. var torus = new BABYLON.Mesh(name, scene);
  15547. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15548. vertexData.applyToMesh(torus, options.updatable);
  15549. return torus;
  15550. };
  15551. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15552. var torusKnot = new BABYLON.Mesh(name, scene);
  15553. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15554. vertexData.applyToMesh(torusKnot, options.updatable);
  15555. return torusKnot;
  15556. };
  15557. MeshBuilder.CreateLines = function (name, options, scene) {
  15558. var instance = options.instance;
  15559. var points = options.points;
  15560. if (instance) {
  15561. var positionFunction = function (positions) {
  15562. var i = 0;
  15563. for (var p = 0; p < points.length; p++) {
  15564. positions[i] = points[p].x;
  15565. positions[i + 1] = points[p].y;
  15566. positions[i + 2] = points[p].z;
  15567. i += 3;
  15568. }
  15569. };
  15570. instance.updateMeshPositions(positionFunction, false);
  15571. return instance;
  15572. }
  15573. // lines creation
  15574. var lines = new BABYLON.LinesMesh(name, scene);
  15575. var vertexData = BABYLON.VertexData.CreateLines(options);
  15576. vertexData.applyToMesh(lines, options.updatable);
  15577. return lines;
  15578. };
  15579. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15580. var points = options.points;
  15581. var instance = options.instance;
  15582. var gapSize = options.gapSize;
  15583. var dashNb = options.dashNb;
  15584. var dashSize = options.dashSize;
  15585. if (instance) {
  15586. var positionFunction = function (positions) {
  15587. var curvect = BABYLON.Vector3.Zero();
  15588. var nbSeg = positions.length / 6;
  15589. var lg = 0;
  15590. var nb = 0;
  15591. var shft = 0;
  15592. var dashshft = 0;
  15593. var curshft = 0;
  15594. var p = 0;
  15595. var i = 0;
  15596. var j = 0;
  15597. for (i = 0; i < points.length - 1; i++) {
  15598. points[i + 1].subtractToRef(points[i], curvect);
  15599. lg += curvect.length();
  15600. }
  15601. shft = lg / nbSeg;
  15602. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15603. for (i = 0; i < points.length - 1; i++) {
  15604. points[i + 1].subtractToRef(points[i], curvect);
  15605. nb = Math.floor(curvect.length() / shft);
  15606. curvect.normalize();
  15607. j = 0;
  15608. while (j < nb && p < positions.length) {
  15609. curshft = shft * j;
  15610. positions[p] = points[i].x + curshft * curvect.x;
  15611. positions[p + 1] = points[i].y + curshft * curvect.y;
  15612. positions[p + 2] = points[i].z + curshft * curvect.z;
  15613. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15614. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15615. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15616. p += 6;
  15617. j++;
  15618. }
  15619. }
  15620. while (p < positions.length) {
  15621. positions[p] = points[i].x;
  15622. positions[p + 1] = points[i].y;
  15623. positions[p + 2] = points[i].z;
  15624. p += 3;
  15625. }
  15626. };
  15627. instance.updateMeshPositions(positionFunction, false);
  15628. return instance;
  15629. }
  15630. // dashed lines creation
  15631. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15632. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15633. vertexData.applyToMesh(dashedLines, options.updatable);
  15634. dashedLines.dashSize = dashSize;
  15635. dashedLines.gapSize = gapSize;
  15636. return dashedLines;
  15637. };
  15638. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15639. var path = options.path;
  15640. var shape = options.shape;
  15641. var scale = options.scale || 1;
  15642. var rotation = options.rotation || 0;
  15643. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15644. var updatable = options.updatable;
  15645. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15646. var instance = options.instance;
  15647. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15648. };
  15649. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15650. var path = options.path;
  15651. var shape = options.shape;
  15652. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15653. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15654. var ribbonCloseArray = options.ribbonCloseArray || false;
  15655. var ribbonClosePath = options.ribbonClosePath || false;
  15656. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15657. var updatable = options.updatable;
  15658. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15659. var instance = options.instance;
  15660. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15661. };
  15662. MeshBuilder.CreateLathe = function (name, options, scene) {
  15663. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15664. var closed = (options.closed === undefined) ? true : options.closed;
  15665. var shape = options.shape;
  15666. var radius = options.radius || 1;
  15667. var tessellation = options.tessellation || 64;
  15668. var updatable = options.updatable;
  15669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15670. var pi2 = Math.PI * 2;
  15671. var shapeLathe = new Array();
  15672. // first rotatable point
  15673. var i = 0;
  15674. while (shape[i].x === 0) {
  15675. i++;
  15676. }
  15677. var pt = shape[i];
  15678. for (i = 0; i < shape.length; i++) {
  15679. shapeLathe.push(shape[i].subtract(pt));
  15680. }
  15681. // circle path
  15682. var step = pi2 / tessellation * arc;
  15683. var rotated;
  15684. var path = new Array();
  15685. ;
  15686. for (i = 0; i <= tessellation; i++) {
  15687. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15688. path.push(rotated);
  15689. }
  15690. if (closed) {
  15691. path.push(path[0]);
  15692. }
  15693. // extrusion
  15694. var scaleFunction = function () { return 1; };
  15695. var rotateFunction = function () { return 0; };
  15696. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15697. return lathe;
  15698. };
  15699. MeshBuilder.CreatePlane = function (name, options, scene) {
  15700. var plane = new BABYLON.Mesh(name, scene);
  15701. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15702. vertexData.applyToMesh(plane, options.updatable);
  15703. if (options.sourcePlane) {
  15704. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15705. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15706. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15707. plane.rotate(vectorProduct, product);
  15708. }
  15709. return plane;
  15710. };
  15711. MeshBuilder.CreateGround = function (name, options, scene) {
  15712. var ground = new BABYLON.GroundMesh(name, scene);
  15713. ground._setReady(false);
  15714. ground._subdivisions = options.subdivisions || 1;
  15715. var vertexData = BABYLON.VertexData.CreateGround(options);
  15716. vertexData.applyToMesh(ground, options.updatable);
  15717. ground._setReady(true);
  15718. return ground;
  15719. };
  15720. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15721. var tiledGround = new BABYLON.Mesh(name, scene);
  15722. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15723. vertexData.applyToMesh(tiledGround, options.updatable);
  15724. return tiledGround;
  15725. };
  15726. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15727. var width = options.width || 10;
  15728. var height = options.height || 10;
  15729. var subdivisions = options.subdivisions || 1;
  15730. var minHeight = options.minHeight;
  15731. var maxHeight = options.maxHeight || 10;
  15732. var updatable = options.updatable;
  15733. var onReady = options.onReady;
  15734. var ground = new BABYLON.GroundMesh(name, scene);
  15735. ground._subdivisions = subdivisions;
  15736. ground._setReady(false);
  15737. var onload = function (img) {
  15738. // Getting height map data
  15739. var canvas = document.createElement("canvas");
  15740. var context = canvas.getContext("2d");
  15741. var bufferWidth = img.width;
  15742. var bufferHeight = img.height;
  15743. canvas.width = bufferWidth;
  15744. canvas.height = bufferHeight;
  15745. context.drawImage(img, 0, 0);
  15746. // Create VertexData from map data
  15747. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15748. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15749. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15750. width: width, height: height,
  15751. subdivisions: subdivisions,
  15752. minHeight: minHeight, maxHeight: maxHeight,
  15753. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15754. });
  15755. vertexData.applyToMesh(ground, updatable);
  15756. ground._setReady(true);
  15757. //execute ready callback, if set
  15758. if (onReady) {
  15759. onReady(ground);
  15760. }
  15761. };
  15762. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15763. return ground;
  15764. };
  15765. MeshBuilder.CreateTube = function (name, options, scene) {
  15766. var path = options.path;
  15767. var radius = options.radius || 1;
  15768. var tessellation = options.tessellation || 64;
  15769. var radiusFunction = options.radiusFunction;
  15770. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15771. var updatable = options.updatable;
  15772. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15773. var instance = options.instance;
  15774. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15775. // tube geometry
  15776. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15777. var tangents = path3D.getTangents();
  15778. var normals = path3D.getNormals();
  15779. var distances = path3D.getDistances();
  15780. var pi2 = Math.PI * 2;
  15781. var step = pi2 / tessellation * arc;
  15782. var returnRadius = function () { return radius; };
  15783. var radiusFunctionFinal = radiusFunction || returnRadius;
  15784. var circlePath;
  15785. var rad;
  15786. var normal;
  15787. var rotated;
  15788. var rotationMatrix = BABYLON.Matrix.Zero();
  15789. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15790. for (var i = 0; i < path.length; i++) {
  15791. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15792. circlePath = Array(); // current circle array
  15793. normal = normals[i]; // current normal
  15794. for (var t = 0; t < tessellation; t++) {
  15795. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15796. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15797. circlePath.push(rotated);
  15798. }
  15799. circlePaths[index] = circlePath;
  15800. index++;
  15801. }
  15802. // cap
  15803. var capPath = function (nbPoints, pathIndex) {
  15804. var pointCap = Array();
  15805. for (var i = 0; i < nbPoints; i++) {
  15806. pointCap.push(path[pathIndex]);
  15807. }
  15808. return pointCap;
  15809. };
  15810. switch (cap) {
  15811. case BABYLON.Mesh.NO_CAP:
  15812. break;
  15813. case BABYLON.Mesh.CAP_START:
  15814. circlePaths[0] = capPath(tessellation, 0);
  15815. circlePaths[1] = circlePaths[2].slice(0);
  15816. break;
  15817. case BABYLON.Mesh.CAP_END:
  15818. circlePaths[index] = circlePaths[index - 1].slice(0);
  15819. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15820. break;
  15821. case BABYLON.Mesh.CAP_ALL:
  15822. circlePaths[0] = capPath(tessellation, 0);
  15823. circlePaths[1] = circlePaths[2].slice(0);
  15824. circlePaths[index] = circlePaths[index - 1].slice(0);
  15825. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15826. break;
  15827. default:
  15828. break;
  15829. }
  15830. return circlePaths;
  15831. };
  15832. var path3D;
  15833. var pathArray;
  15834. if (instance) {
  15835. var arc = options.arc || instance.arc;
  15836. path3D = (instance.path3D).update(path);
  15837. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15838. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15839. instance.path3D = path3D;
  15840. instance.pathArray = pathArray;
  15841. instance.arc = arc;
  15842. return instance;
  15843. }
  15844. // tube creation
  15845. path3D = new BABYLON.Path3D(path);
  15846. var newPathArray = new Array();
  15847. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15848. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15849. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15850. tube.pathArray = pathArray;
  15851. tube.path3D = path3D;
  15852. tube.tessellation = tessellation;
  15853. tube.cap = cap;
  15854. tube.arc = options.arc;
  15855. return tube;
  15856. };
  15857. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15858. var polyhedron = new BABYLON.Mesh(name, scene);
  15859. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15860. vertexData.applyToMesh(polyhedron, options.updatable);
  15861. return polyhedron;
  15862. };
  15863. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15864. var indices = sourceMesh.getIndices();
  15865. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15866. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15867. var position = options.position || BABYLON.Vector3.Zero();
  15868. var normal = options.normal || BABYLON.Vector3.Up();
  15869. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15870. var angle = options.angle || 0;
  15871. // Getting correct rotation
  15872. if (!normal) {
  15873. var target = new BABYLON.Vector3(0, 0, 1);
  15874. var camera = sourceMesh.getScene().activeCamera;
  15875. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15876. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15877. }
  15878. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15879. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15880. var pitch = Math.atan2(normal.y, len);
  15881. // Matrix
  15882. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15883. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15884. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15885. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15886. var vertexData = new BABYLON.VertexData();
  15887. vertexData.indices = [];
  15888. vertexData.positions = [];
  15889. vertexData.normals = [];
  15890. vertexData.uvs = [];
  15891. var currentVertexDataIndex = 0;
  15892. var extractDecalVector3 = function (indexId) {
  15893. var vertexId = indices[indexId];
  15894. var result = new BABYLON.PositionNormalVertex();
  15895. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15896. // Send vector to decal local world
  15897. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15898. // Get normal
  15899. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15900. return result;
  15901. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15902. var clip = function (vertices, axis) {
  15903. if (vertices.length === 0) {
  15904. return vertices;
  15905. }
  15906. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15907. var clipVertices = function (v0, v1) {
  15908. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15909. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15910. };
  15911. var result = new Array();
  15912. for (var index = 0; index < vertices.length; index += 3) {
  15913. var v1Out;
  15914. var v2Out;
  15915. var v3Out;
  15916. var total = 0;
  15917. var nV1, nV2, nV3, nV4;
  15918. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15919. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15920. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15921. v1Out = d1 > 0;
  15922. v2Out = d2 > 0;
  15923. v3Out = d3 > 0;
  15924. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15925. switch (total) {
  15926. case 0:
  15927. result.push(vertices[index]);
  15928. result.push(vertices[index + 1]);
  15929. result.push(vertices[index + 2]);
  15930. break;
  15931. case 1:
  15932. if (v1Out) {
  15933. nV1 = vertices[index + 1];
  15934. nV2 = vertices[index + 2];
  15935. nV3 = clipVertices(vertices[index], nV1);
  15936. nV4 = clipVertices(vertices[index], nV2);
  15937. }
  15938. if (v2Out) {
  15939. nV1 = vertices[index];
  15940. nV2 = vertices[index + 2];
  15941. nV3 = clipVertices(vertices[index + 1], nV1);
  15942. nV4 = clipVertices(vertices[index + 1], nV2);
  15943. result.push(nV3);
  15944. result.push(nV2.clone());
  15945. result.push(nV1.clone());
  15946. result.push(nV2.clone());
  15947. result.push(nV3.clone());
  15948. result.push(nV4);
  15949. break;
  15950. }
  15951. if (v3Out) {
  15952. nV1 = vertices[index];
  15953. nV2 = vertices[index + 1];
  15954. nV3 = clipVertices(vertices[index + 2], nV1);
  15955. nV4 = clipVertices(vertices[index + 2], nV2);
  15956. }
  15957. result.push(nV1.clone());
  15958. result.push(nV2.clone());
  15959. result.push(nV3);
  15960. result.push(nV4);
  15961. result.push(nV3.clone());
  15962. result.push(nV2.clone());
  15963. break;
  15964. case 2:
  15965. if (!v1Out) {
  15966. nV1 = vertices[index].clone();
  15967. nV2 = clipVertices(nV1, vertices[index + 1]);
  15968. nV3 = clipVertices(nV1, vertices[index + 2]);
  15969. result.push(nV1);
  15970. result.push(nV2);
  15971. result.push(nV3);
  15972. }
  15973. if (!v2Out) {
  15974. nV1 = vertices[index + 1].clone();
  15975. nV2 = clipVertices(nV1, vertices[index + 2]);
  15976. nV3 = clipVertices(nV1, vertices[index]);
  15977. result.push(nV1);
  15978. result.push(nV2);
  15979. result.push(nV3);
  15980. }
  15981. if (!v3Out) {
  15982. nV1 = vertices[index + 2].clone();
  15983. nV2 = clipVertices(nV1, vertices[index]);
  15984. nV3 = clipVertices(nV1, vertices[index + 1]);
  15985. result.push(nV1);
  15986. result.push(nV2);
  15987. result.push(nV3);
  15988. }
  15989. break;
  15990. case 3:
  15991. break;
  15992. }
  15993. }
  15994. return result;
  15995. };
  15996. for (var index = 0; index < indices.length; index += 3) {
  15997. var faceVertices = new Array();
  15998. faceVertices.push(extractDecalVector3(index));
  15999. faceVertices.push(extractDecalVector3(index + 1));
  16000. faceVertices.push(extractDecalVector3(index + 2));
  16001. // Clip
  16002. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16003. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16008. if (faceVertices.length === 0) {
  16009. continue;
  16010. }
  16011. // Add UVs and get back to world
  16012. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16013. var vertex = faceVertices[vIndex];
  16014. vertexData.indices.push(currentVertexDataIndex);
  16015. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16016. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16017. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16018. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16019. currentVertexDataIndex++;
  16020. }
  16021. }
  16022. // Return mesh
  16023. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16024. vertexData.applyToMesh(decal);
  16025. decal.position = position.clone();
  16026. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16027. return decal;
  16028. };
  16029. // Privates
  16030. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16031. // extrusion geometry
  16032. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16033. var tangents = path3D.getTangents();
  16034. var normals = path3D.getNormals();
  16035. var binormals = path3D.getBinormals();
  16036. var distances = path3D.getDistances();
  16037. var angle = 0;
  16038. var returnScale = function () { return scale; };
  16039. var returnRotation = function () { return rotation; };
  16040. var rotate = custom ? rotateFunction : returnRotation;
  16041. var scl = custom ? scaleFunction : returnScale;
  16042. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16043. var rotationMatrix = BABYLON.Matrix.Zero();
  16044. for (var i = 0; i < curve.length; i++) {
  16045. var shapePath = new Array();
  16046. var angleStep = rotate(i, distances[i]);
  16047. var scaleRatio = scl(i, distances[i]);
  16048. for (var p = 0; p < shape.length; p++) {
  16049. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16050. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16051. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16052. shapePath.push(rotated);
  16053. }
  16054. shapePaths[index] = shapePath;
  16055. angle += angleStep;
  16056. index++;
  16057. }
  16058. // cap
  16059. var capPath = function (shapePath) {
  16060. var pointCap = Array();
  16061. var barycenter = BABYLON.Vector3.Zero();
  16062. var i;
  16063. for (i = 0; i < shapePath.length; i++) {
  16064. barycenter.addInPlace(shapePath[i]);
  16065. }
  16066. barycenter.scaleInPlace(1 / shapePath.length);
  16067. for (i = 0; i < shapePath.length; i++) {
  16068. pointCap.push(barycenter);
  16069. }
  16070. return pointCap;
  16071. };
  16072. switch (cap) {
  16073. case BABYLON.Mesh.NO_CAP:
  16074. break;
  16075. case BABYLON.Mesh.CAP_START:
  16076. shapePaths[0] = capPath(shapePaths[2]);
  16077. shapePaths[1] = shapePaths[2].slice(0);
  16078. break;
  16079. case BABYLON.Mesh.CAP_END:
  16080. shapePaths[index] = shapePaths[index - 1];
  16081. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16082. break;
  16083. case BABYLON.Mesh.CAP_ALL:
  16084. shapePaths[0] = capPath(shapePaths[2]);
  16085. shapePaths[1] = shapePaths[2].slice(0);
  16086. shapePaths[index] = shapePaths[index - 1];
  16087. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16088. break;
  16089. default:
  16090. break;
  16091. }
  16092. return shapePaths;
  16093. };
  16094. var path3D;
  16095. var pathArray;
  16096. if (instance) {
  16097. path3D = (instance.path3D).update(curve);
  16098. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16099. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16100. return instance;
  16101. }
  16102. // extruded shape creation
  16103. path3D = new BABYLON.Path3D(curve);
  16104. var newShapePaths = new Array();
  16105. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16106. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16107. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16108. extrudedGeneric.pathArray = pathArray;
  16109. extrudedGeneric.path3D = path3D;
  16110. extrudedGeneric.cap = cap;
  16111. return extrudedGeneric;
  16112. };
  16113. return MeshBuilder;
  16114. })();
  16115. BABYLON.MeshBuilder = MeshBuilder;
  16116. })(BABYLON || (BABYLON = {}));
  16117. var BABYLON;
  16118. (function (BABYLON) {
  16119. var BaseTexture = (function () {
  16120. function BaseTexture(scene) {
  16121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16122. this.hasAlpha = false;
  16123. this.getAlphaFromRGB = false;
  16124. this.level = 1;
  16125. this.isCube = false;
  16126. this.isRenderTarget = false;
  16127. this.animations = new Array();
  16128. this.coordinatesIndex = 0;
  16129. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16130. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16131. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16132. this.anisotropicFilteringLevel = 4;
  16133. this._scene = scene;
  16134. this._scene.textures.push(this);
  16135. }
  16136. BaseTexture.prototype.getScene = function () {
  16137. return this._scene;
  16138. };
  16139. BaseTexture.prototype.getTextureMatrix = function () {
  16140. return null;
  16141. };
  16142. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16143. return null;
  16144. };
  16145. BaseTexture.prototype.getInternalTexture = function () {
  16146. return this._texture;
  16147. };
  16148. BaseTexture.prototype.isReady = function () {
  16149. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16150. return true;
  16151. }
  16152. if (this._texture) {
  16153. return this._texture.isReady;
  16154. }
  16155. return false;
  16156. };
  16157. BaseTexture.prototype.getSize = function () {
  16158. if (this._texture._width) {
  16159. return { width: this._texture._width, height: this._texture._height };
  16160. }
  16161. if (this._texture._size) {
  16162. return { width: this._texture._size, height: this._texture._size };
  16163. }
  16164. return { width: 0, height: 0 };
  16165. };
  16166. BaseTexture.prototype.getBaseSize = function () {
  16167. if (!this.isReady())
  16168. return { width: 0, height: 0 };
  16169. if (this._texture._size) {
  16170. return { width: this._texture._size, height: this._texture._size };
  16171. }
  16172. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16173. };
  16174. BaseTexture.prototype.scale = function (ratio) {
  16175. };
  16176. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16177. get: function () {
  16178. return false;
  16179. },
  16180. enumerable: true,
  16181. configurable: true
  16182. });
  16183. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16184. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16185. for (var index = 0; index < texturesCache.length; index++) {
  16186. var texturesCacheEntry = texturesCache[index];
  16187. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16188. texturesCache.splice(index, 1);
  16189. return;
  16190. }
  16191. }
  16192. };
  16193. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16194. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16195. for (var index = 0; index < texturesCache.length; index++) {
  16196. var texturesCacheEntry = texturesCache[index];
  16197. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16198. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16199. texturesCacheEntry.references++;
  16200. return texturesCacheEntry;
  16201. }
  16202. }
  16203. }
  16204. return null;
  16205. };
  16206. BaseTexture.prototype.delayLoad = function () {
  16207. };
  16208. BaseTexture.prototype.clone = function () {
  16209. return null;
  16210. };
  16211. BaseTexture.prototype.releaseInternalTexture = function () {
  16212. if (this._texture) {
  16213. this._scene.getEngine().releaseInternalTexture(this._texture);
  16214. delete this._texture;
  16215. }
  16216. };
  16217. BaseTexture.prototype.dispose = function () {
  16218. // Animations
  16219. this.getScene().stopAnimation(this);
  16220. // Remove from scene
  16221. var index = this._scene.textures.indexOf(this);
  16222. if (index >= 0) {
  16223. this._scene.textures.splice(index, 1);
  16224. }
  16225. if (this._texture === undefined) {
  16226. return;
  16227. }
  16228. // Callback
  16229. if (this.onDispose) {
  16230. this.onDispose();
  16231. }
  16232. };
  16233. return BaseTexture;
  16234. })();
  16235. BABYLON.BaseTexture = BaseTexture;
  16236. })(BABYLON || (BABYLON = {}));
  16237. var BABYLON;
  16238. (function (BABYLON) {
  16239. var Texture = (function (_super) {
  16240. __extends(Texture, _super);
  16241. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16242. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16243. if (onLoad === void 0) { onLoad = null; }
  16244. if (onError === void 0) { onError = null; }
  16245. if (buffer === void 0) { buffer = null; }
  16246. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16247. _super.call(this, scene);
  16248. this.uOffset = 0;
  16249. this.vOffset = 0;
  16250. this.uScale = 1.0;
  16251. this.vScale = 1.0;
  16252. this.uAng = 0;
  16253. this.vAng = 0;
  16254. this.wAng = 0;
  16255. this.name = url;
  16256. this.url = url;
  16257. this._noMipmap = noMipmap;
  16258. this._invertY = invertY;
  16259. this._samplingMode = samplingMode;
  16260. this._buffer = buffer;
  16261. this._deleteBuffer = deleteBuffer;
  16262. if (!url) {
  16263. return;
  16264. }
  16265. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16266. if (!this._texture) {
  16267. if (!scene.useDelayedTextureLoading) {
  16268. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16269. if (deleteBuffer) {
  16270. delete this._buffer;
  16271. }
  16272. }
  16273. else {
  16274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16275. }
  16276. }
  16277. else {
  16278. BABYLON.Tools.SetImmediate(function () {
  16279. if (onLoad) {
  16280. onLoad();
  16281. }
  16282. });
  16283. }
  16284. }
  16285. Texture.prototype.delayLoad = function () {
  16286. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16287. return;
  16288. }
  16289. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16290. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16291. if (!this._texture) {
  16292. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16293. if (this._deleteBuffer) {
  16294. delete this._buffer;
  16295. }
  16296. }
  16297. };
  16298. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16299. if (!this._texture) {
  16300. return;
  16301. }
  16302. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16303. };
  16304. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16305. x *= this.uScale;
  16306. y *= this.vScale;
  16307. x -= 0.5 * this.uScale;
  16308. y -= 0.5 * this.vScale;
  16309. z -= 0.5;
  16310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16311. t.x += 0.5 * this.uScale + this.uOffset;
  16312. t.y += 0.5 * this.vScale + this.vOffset;
  16313. t.z += 0.5;
  16314. };
  16315. Texture.prototype.getTextureMatrix = function () {
  16316. if (this.uOffset === this._cachedUOffset &&
  16317. this.vOffset === this._cachedVOffset &&
  16318. this.uScale === this._cachedUScale &&
  16319. this.vScale === this._cachedVScale &&
  16320. this.uAng === this._cachedUAng &&
  16321. this.vAng === this._cachedVAng &&
  16322. this.wAng === this._cachedWAng) {
  16323. return this._cachedTextureMatrix;
  16324. }
  16325. this._cachedUOffset = this.uOffset;
  16326. this._cachedVOffset = this.vOffset;
  16327. this._cachedUScale = this.uScale;
  16328. this._cachedVScale = this.vScale;
  16329. this._cachedUAng = this.uAng;
  16330. this._cachedVAng = this.vAng;
  16331. this._cachedWAng = this.wAng;
  16332. if (!this._cachedTextureMatrix) {
  16333. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16334. this._rowGenerationMatrix = new BABYLON.Matrix();
  16335. this._t0 = BABYLON.Vector3.Zero();
  16336. this._t1 = BABYLON.Vector3.Zero();
  16337. this._t2 = BABYLON.Vector3.Zero();
  16338. }
  16339. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16340. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16341. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16342. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16343. this._t1.subtractInPlace(this._t0);
  16344. this._t2.subtractInPlace(this._t0);
  16345. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16346. this._cachedTextureMatrix.m[0] = this._t1.x;
  16347. this._cachedTextureMatrix.m[1] = this._t1.y;
  16348. this._cachedTextureMatrix.m[2] = this._t1.z;
  16349. this._cachedTextureMatrix.m[4] = this._t2.x;
  16350. this._cachedTextureMatrix.m[5] = this._t2.y;
  16351. this._cachedTextureMatrix.m[6] = this._t2.z;
  16352. this._cachedTextureMatrix.m[8] = this._t0.x;
  16353. this._cachedTextureMatrix.m[9] = this._t0.y;
  16354. this._cachedTextureMatrix.m[10] = this._t0.z;
  16355. return this._cachedTextureMatrix;
  16356. };
  16357. Texture.prototype.getReflectionTextureMatrix = function () {
  16358. if (this.uOffset === this._cachedUOffset &&
  16359. this.vOffset === this._cachedVOffset &&
  16360. this.uScale === this._cachedUScale &&
  16361. this.vScale === this._cachedVScale &&
  16362. this.coordinatesMode === this._cachedCoordinatesMode) {
  16363. return this._cachedTextureMatrix;
  16364. }
  16365. if (!this._cachedTextureMatrix) {
  16366. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16367. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16368. }
  16369. this._cachedCoordinatesMode = this.coordinatesMode;
  16370. switch (this.coordinatesMode) {
  16371. case Texture.PLANAR_MODE:
  16372. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16373. this._cachedTextureMatrix[0] = this.uScale;
  16374. this._cachedTextureMatrix[5] = this.vScale;
  16375. this._cachedTextureMatrix[12] = this.uOffset;
  16376. this._cachedTextureMatrix[13] = this.vOffset;
  16377. break;
  16378. case Texture.PROJECTION_MODE:
  16379. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16380. this._projectionModeMatrix.m[0] = 0.5;
  16381. this._projectionModeMatrix.m[5] = -0.5;
  16382. this._projectionModeMatrix.m[10] = 0.0;
  16383. this._projectionModeMatrix.m[12] = 0.5;
  16384. this._projectionModeMatrix.m[13] = 0.5;
  16385. this._projectionModeMatrix.m[14] = 1.0;
  16386. this._projectionModeMatrix.m[15] = 1.0;
  16387. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16388. break;
  16389. default:
  16390. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16391. break;
  16392. }
  16393. return this._cachedTextureMatrix;
  16394. };
  16395. Texture.prototype.clone = function () {
  16396. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16397. // Base texture
  16398. newTexture.hasAlpha = this.hasAlpha;
  16399. newTexture.level = this.level;
  16400. newTexture.wrapU = this.wrapU;
  16401. newTexture.wrapV = this.wrapV;
  16402. newTexture.coordinatesIndex = this.coordinatesIndex;
  16403. newTexture.coordinatesMode = this.coordinatesMode;
  16404. // Texture
  16405. newTexture.uOffset = this.uOffset;
  16406. newTexture.vOffset = this.vOffset;
  16407. newTexture.uScale = this.uScale;
  16408. newTexture.vScale = this.vScale;
  16409. newTexture.uAng = this.uAng;
  16410. newTexture.vAng = this.vAng;
  16411. newTexture.wAng = this.wAng;
  16412. return newTexture;
  16413. };
  16414. // Statics
  16415. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16416. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16417. if (onLoad === void 0) { onLoad = null; }
  16418. if (onError === void 0) { onError = null; }
  16419. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16420. };
  16421. // Constants
  16422. Texture.NEAREST_SAMPLINGMODE = 1;
  16423. Texture.BILINEAR_SAMPLINGMODE = 2;
  16424. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16425. Texture.EXPLICIT_MODE = 0;
  16426. Texture.SPHERICAL_MODE = 1;
  16427. Texture.PLANAR_MODE = 2;
  16428. Texture.CUBIC_MODE = 3;
  16429. Texture.PROJECTION_MODE = 4;
  16430. Texture.SKYBOX_MODE = 5;
  16431. Texture.INVCUBIC_MODE = 6;
  16432. Texture.EQUIRECTANGULAR_MODE = 7;
  16433. Texture.CLAMP_ADDRESSMODE = 0;
  16434. Texture.WRAP_ADDRESSMODE = 1;
  16435. Texture.MIRROR_ADDRESSMODE = 2;
  16436. return Texture;
  16437. })(BABYLON.BaseTexture);
  16438. BABYLON.Texture = Texture;
  16439. })(BABYLON || (BABYLON = {}));
  16440. var BABYLON;
  16441. (function (BABYLON) {
  16442. var CubeTexture = (function (_super) {
  16443. __extends(CubeTexture, _super);
  16444. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16445. _super.call(this, scene);
  16446. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16447. this.name = rootUrl;
  16448. this.url = rootUrl;
  16449. this._noMipmap = noMipmap;
  16450. this.hasAlpha = false;
  16451. if (!rootUrl) {
  16452. return;
  16453. }
  16454. this._texture = this._getFromCache(rootUrl, noMipmap);
  16455. if (!extensions) {
  16456. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16457. }
  16458. this._extensions = extensions;
  16459. if (!this._texture) {
  16460. if (!scene.useDelayedTextureLoading) {
  16461. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16462. }
  16463. else {
  16464. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16465. }
  16466. }
  16467. this.isCube = true;
  16468. this._textureMatrix = BABYLON.Matrix.Identity();
  16469. }
  16470. CubeTexture.prototype.clone = function () {
  16471. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16472. // Base texture
  16473. newTexture.level = this.level;
  16474. newTexture.wrapU = this.wrapU;
  16475. newTexture.wrapV = this.wrapV;
  16476. newTexture.coordinatesIndex = this.coordinatesIndex;
  16477. newTexture.coordinatesMode = this.coordinatesMode;
  16478. return newTexture;
  16479. };
  16480. // Methods
  16481. CubeTexture.prototype.delayLoad = function () {
  16482. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16483. return;
  16484. }
  16485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16486. this._texture = this._getFromCache(this.url, this._noMipmap);
  16487. if (!this._texture) {
  16488. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16489. }
  16490. };
  16491. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16492. return this._textureMatrix;
  16493. };
  16494. return CubeTexture;
  16495. })(BABYLON.BaseTexture);
  16496. BABYLON.CubeTexture = CubeTexture;
  16497. })(BABYLON || (BABYLON = {}));
  16498. var BABYLON;
  16499. (function (BABYLON) {
  16500. var RenderTargetTexture = (function (_super) {
  16501. __extends(RenderTargetTexture, _super);
  16502. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16503. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16505. if (isCube === void 0) { isCube = false; }
  16506. _super.call(this, null, scene, !generateMipMaps);
  16507. this.isCube = isCube;
  16508. this.renderList = new Array();
  16509. this.renderParticles = true;
  16510. this.renderSprites = false;
  16511. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16512. this._currentRefreshId = -1;
  16513. this._refreshRate = 1;
  16514. this.name = name;
  16515. this.isRenderTarget = true;
  16516. this._size = size;
  16517. this._generateMipMaps = generateMipMaps;
  16518. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16519. if (isCube) {
  16520. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16521. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16522. this._textureMatrix = BABYLON.Matrix.Identity();
  16523. }
  16524. else {
  16525. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16526. }
  16527. // Rendering groups
  16528. this._renderingManager = new BABYLON.RenderingManager(scene);
  16529. }
  16530. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16531. get: function () {
  16532. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16533. },
  16534. enumerable: true,
  16535. configurable: true
  16536. });
  16537. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16538. get: function () {
  16539. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16540. },
  16541. enumerable: true,
  16542. configurable: true
  16543. });
  16544. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16545. get: function () {
  16546. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16547. },
  16548. enumerable: true,
  16549. configurable: true
  16550. });
  16551. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16552. this._currentRefreshId = -1;
  16553. };
  16554. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16555. get: function () {
  16556. return this._refreshRate;
  16557. },
  16558. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16559. set: function (value) {
  16560. this._refreshRate = value;
  16561. this.resetRefreshCounter();
  16562. },
  16563. enumerable: true,
  16564. configurable: true
  16565. });
  16566. RenderTargetTexture.prototype._shouldRender = function () {
  16567. if (this._currentRefreshId === -1) {
  16568. this._currentRefreshId = 1;
  16569. return true;
  16570. }
  16571. if (this.refreshRate === this._currentRefreshId) {
  16572. this._currentRefreshId = 1;
  16573. return true;
  16574. }
  16575. this._currentRefreshId++;
  16576. return false;
  16577. };
  16578. RenderTargetTexture.prototype.isReady = function () {
  16579. if (!this.getScene().renderTargetsEnabled) {
  16580. return false;
  16581. }
  16582. return _super.prototype.isReady.call(this);
  16583. };
  16584. RenderTargetTexture.prototype.getRenderSize = function () {
  16585. return this._size;
  16586. };
  16587. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16588. get: function () {
  16589. return true;
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. RenderTargetTexture.prototype.scale = function (ratio) {
  16595. var newSize = this._size * ratio;
  16596. this.resize(newSize, this._generateMipMaps);
  16597. };
  16598. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16599. if (this.isCube) {
  16600. return this._textureMatrix;
  16601. }
  16602. return _super.prototype.getReflectionTextureMatrix.call(this);
  16603. };
  16604. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16605. this.releaseInternalTexture();
  16606. if (this.isCube) {
  16607. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16608. }
  16609. else {
  16610. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16611. }
  16612. };
  16613. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16614. var scene = this.getScene();
  16615. if (this._waitingRenderList) {
  16616. this.renderList = [];
  16617. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16618. var id = this._waitingRenderList[index];
  16619. this.renderList.push(scene.getMeshByID(id));
  16620. }
  16621. delete this._waitingRenderList;
  16622. }
  16623. if (this.renderList && this.renderList.length === 0) {
  16624. return;
  16625. }
  16626. // Prepare renderingManager
  16627. this._renderingManager.reset();
  16628. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16629. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16630. var mesh = currentRenderList[meshIndex];
  16631. if (mesh) {
  16632. if (!mesh.isReady()) {
  16633. // Reset _currentRefreshId
  16634. this.resetRefreshCounter();
  16635. continue;
  16636. }
  16637. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16638. mesh._activate(scene.getRenderId());
  16639. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16640. var subMesh = mesh.subMeshes[subIndex];
  16641. scene._activeIndices += subMesh.indexCount;
  16642. this._renderingManager.dispatch(subMesh);
  16643. }
  16644. }
  16645. }
  16646. }
  16647. if (this.isCube) {
  16648. for (var face = 0; face < 6; face++) {
  16649. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16650. }
  16651. }
  16652. else {
  16653. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16654. }
  16655. if (this.onAfterUnbind) {
  16656. this.onAfterUnbind();
  16657. }
  16658. scene.resetCachedMaterial();
  16659. };
  16660. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16661. var scene = this.getScene();
  16662. var engine = scene.getEngine();
  16663. // Bind
  16664. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16665. if (this.isCube) {
  16666. engine.bindFramebuffer(this._texture, faceIndex);
  16667. }
  16668. else {
  16669. engine.bindFramebuffer(this._texture);
  16670. }
  16671. }
  16672. if (this.onBeforeRender) {
  16673. this.onBeforeRender(faceIndex);
  16674. }
  16675. // Clear
  16676. if (this.onClear) {
  16677. this.onClear(engine);
  16678. }
  16679. else {
  16680. engine.clear(scene.clearColor, true, true);
  16681. }
  16682. if (!this._doNotChangeAspectRatio) {
  16683. scene.updateTransformMatrix(true);
  16684. }
  16685. // Render
  16686. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16687. if (useCameraPostProcess) {
  16688. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16689. }
  16690. if (!this._doNotChangeAspectRatio) {
  16691. scene.updateTransformMatrix(true);
  16692. }
  16693. if (this.onAfterRender) {
  16694. this.onAfterRender(faceIndex);
  16695. }
  16696. // Dump ?
  16697. if (dumpForDebug) {
  16698. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16699. }
  16700. // Unbind
  16701. if (!this.isCube || faceIndex === 5) {
  16702. if (this.isCube) {
  16703. if (faceIndex === 5) {
  16704. engine.generateMipMapsForCubemap(this._texture);
  16705. }
  16706. }
  16707. engine.unBindFramebuffer(this._texture, this.isCube);
  16708. }
  16709. };
  16710. RenderTargetTexture.prototype.clone = function () {
  16711. var textureSize = this.getSize();
  16712. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16713. // Base texture
  16714. newTexture.hasAlpha = this.hasAlpha;
  16715. newTexture.level = this.level;
  16716. // RenderTarget Texture
  16717. newTexture.coordinatesMode = this.coordinatesMode;
  16718. newTexture.renderList = this.renderList.slice(0);
  16719. return newTexture;
  16720. };
  16721. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16722. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16723. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16724. return RenderTargetTexture;
  16725. })(BABYLON.Texture);
  16726. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16727. })(BABYLON || (BABYLON = {}));
  16728. var BABYLON;
  16729. (function (BABYLON) {
  16730. var ProceduralTexture = (function (_super) {
  16731. __extends(ProceduralTexture, _super);
  16732. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16734. _super.call(this, null, scene, !generateMipMaps);
  16735. this.isEnabled = true;
  16736. this._currentRefreshId = -1;
  16737. this._refreshRate = 1;
  16738. this._vertexDeclaration = [2];
  16739. this._vertexStrideSize = 2 * 4;
  16740. this._uniforms = new Array();
  16741. this._samplers = new Array();
  16742. this._textures = new Array();
  16743. this._floats = new Array();
  16744. this._floatsArrays = {};
  16745. this._colors3 = new Array();
  16746. this._colors4 = new Array();
  16747. this._vectors2 = new Array();
  16748. this._vectors3 = new Array();
  16749. this._matrices = new Array();
  16750. this._fallbackTextureUsed = false;
  16751. scene._proceduralTextures.push(this);
  16752. this.name = name;
  16753. this.isRenderTarget = true;
  16754. this._size = size;
  16755. this._generateMipMaps = generateMipMaps;
  16756. this.setFragment(fragment);
  16757. this._fallbackTexture = fallbackTexture;
  16758. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16759. // VBO
  16760. var vertices = [];
  16761. vertices.push(1, 1);
  16762. vertices.push(-1, 1);
  16763. vertices.push(-1, -1);
  16764. vertices.push(1, -1);
  16765. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16766. // Indices
  16767. var indices = [];
  16768. indices.push(0);
  16769. indices.push(1);
  16770. indices.push(2);
  16771. indices.push(0);
  16772. indices.push(2);
  16773. indices.push(3);
  16774. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16775. }
  16776. ProceduralTexture.prototype.reset = function () {
  16777. if (this._effect === undefined) {
  16778. return;
  16779. }
  16780. var engine = this.getScene().getEngine();
  16781. engine._releaseEffect(this._effect);
  16782. };
  16783. ProceduralTexture.prototype.isReady = function () {
  16784. var _this = this;
  16785. var engine = this.getScene().getEngine();
  16786. var shaders;
  16787. if (!this._fragment) {
  16788. return false;
  16789. }
  16790. if (this._fallbackTextureUsed) {
  16791. return true;
  16792. }
  16793. if (this._fragment.fragmentElement !== undefined) {
  16794. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16795. }
  16796. else {
  16797. shaders = { vertex: "procedural", fragment: this._fragment };
  16798. }
  16799. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16800. _this.releaseInternalTexture();
  16801. if (_this._fallbackTexture) {
  16802. _this._texture = _this._fallbackTexture._texture;
  16803. _this._texture.references++;
  16804. }
  16805. _this._fallbackTextureUsed = true;
  16806. });
  16807. return this._effect.isReady();
  16808. };
  16809. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16810. this._currentRefreshId = -1;
  16811. };
  16812. ProceduralTexture.prototype.setFragment = function (fragment) {
  16813. this._fragment = fragment;
  16814. };
  16815. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16816. get: function () {
  16817. return this._refreshRate;
  16818. },
  16819. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16820. set: function (value) {
  16821. this._refreshRate = value;
  16822. this.resetRefreshCounter();
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. ProceduralTexture.prototype._shouldRender = function () {
  16828. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16829. return false;
  16830. }
  16831. if (this._fallbackTextureUsed) {
  16832. return false;
  16833. }
  16834. if (this._currentRefreshId === -1) {
  16835. this._currentRefreshId = 1;
  16836. return true;
  16837. }
  16838. if (this.refreshRate === this._currentRefreshId) {
  16839. this._currentRefreshId = 1;
  16840. return true;
  16841. }
  16842. this._currentRefreshId++;
  16843. return false;
  16844. };
  16845. ProceduralTexture.prototype.getRenderSize = function () {
  16846. return this._size;
  16847. };
  16848. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16849. if (this._fallbackTextureUsed) {
  16850. return;
  16851. }
  16852. this.releaseInternalTexture();
  16853. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16854. };
  16855. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16856. if (this._uniforms.indexOf(uniformName) === -1) {
  16857. this._uniforms.push(uniformName);
  16858. }
  16859. };
  16860. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16861. if (this._samplers.indexOf(name) === -1) {
  16862. this._samplers.push(name);
  16863. }
  16864. this._textures[name] = texture;
  16865. return this;
  16866. };
  16867. ProceduralTexture.prototype.setFloat = function (name, value) {
  16868. this._checkUniform(name);
  16869. this._floats[name] = value;
  16870. return this;
  16871. };
  16872. ProceduralTexture.prototype.setFloats = function (name, value) {
  16873. this._checkUniform(name);
  16874. this._floatsArrays[name] = value;
  16875. return this;
  16876. };
  16877. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16878. this._checkUniform(name);
  16879. this._colors3[name] = value;
  16880. return this;
  16881. };
  16882. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16883. this._checkUniform(name);
  16884. this._colors4[name] = value;
  16885. return this;
  16886. };
  16887. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16888. this._checkUniform(name);
  16889. this._vectors2[name] = value;
  16890. return this;
  16891. };
  16892. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16893. this._checkUniform(name);
  16894. this._vectors3[name] = value;
  16895. return this;
  16896. };
  16897. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16898. this._checkUniform(name);
  16899. this._matrices[name] = value;
  16900. return this;
  16901. };
  16902. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16903. var scene = this.getScene();
  16904. var engine = scene.getEngine();
  16905. engine.bindFramebuffer(this._texture);
  16906. // Clear
  16907. engine.clear(scene.clearColor, true, true);
  16908. // Render
  16909. engine.enableEffect(this._effect);
  16910. engine.setState(false);
  16911. // Texture
  16912. for (var name in this._textures) {
  16913. this._effect.setTexture(name, this._textures[name]);
  16914. }
  16915. // Float
  16916. for (name in this._floats) {
  16917. this._effect.setFloat(name, this._floats[name]);
  16918. }
  16919. // Floats
  16920. for (name in this._floatsArrays) {
  16921. this._effect.setArray(name, this._floatsArrays[name]);
  16922. }
  16923. // Color3
  16924. for (name in this._colors3) {
  16925. this._effect.setColor3(name, this._colors3[name]);
  16926. }
  16927. // Color4
  16928. for (name in this._colors4) {
  16929. var color = this._colors4[name];
  16930. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16931. }
  16932. // Vector2
  16933. for (name in this._vectors2) {
  16934. this._effect.setVector2(name, this._vectors2[name]);
  16935. }
  16936. // Vector3
  16937. for (name in this._vectors3) {
  16938. this._effect.setVector3(name, this._vectors3[name]);
  16939. }
  16940. // Matrix
  16941. for (name in this._matrices) {
  16942. this._effect.setMatrix(name, this._matrices[name]);
  16943. }
  16944. // VBOs
  16945. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16946. // Draw order
  16947. engine.draw(true, 0, 6);
  16948. // Unbind
  16949. engine.unBindFramebuffer(this._texture);
  16950. };
  16951. ProceduralTexture.prototype.clone = function () {
  16952. var textureSize = this.getSize();
  16953. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16954. // Base texture
  16955. newTexture.hasAlpha = this.hasAlpha;
  16956. newTexture.level = this.level;
  16957. // RenderTarget Texture
  16958. newTexture.coordinatesMode = this.coordinatesMode;
  16959. return newTexture;
  16960. };
  16961. ProceduralTexture.prototype.dispose = function () {
  16962. var index = this.getScene()._proceduralTextures.indexOf(this);
  16963. if (index >= 0) {
  16964. this.getScene()._proceduralTextures.splice(index, 1);
  16965. }
  16966. _super.prototype.dispose.call(this);
  16967. };
  16968. return ProceduralTexture;
  16969. })(BABYLON.Texture);
  16970. BABYLON.ProceduralTexture = ProceduralTexture;
  16971. })(BABYLON || (BABYLON = {}));
  16972. var BABYLON;
  16973. (function (BABYLON) {
  16974. var MirrorTexture = (function (_super) {
  16975. __extends(MirrorTexture, _super);
  16976. function MirrorTexture(name, size, scene, generateMipMaps) {
  16977. var _this = this;
  16978. _super.call(this, name, size, scene, generateMipMaps, true);
  16979. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16980. this._transformMatrix = BABYLON.Matrix.Zero();
  16981. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16982. this.onBeforeRender = function () {
  16983. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16984. _this._savedViewMatrix = scene.getViewMatrix();
  16985. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16986. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16987. scene.clipPlane = _this.mirrorPlane;
  16988. scene.getEngine().cullBackFaces = false;
  16989. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16990. };
  16991. this.onAfterRender = function () {
  16992. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16993. scene.getEngine().cullBackFaces = true;
  16994. scene._mirroredCameraPosition = null;
  16995. delete scene.clipPlane;
  16996. };
  16997. }
  16998. MirrorTexture.prototype.clone = function () {
  16999. var textureSize = this.getSize();
  17000. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17001. // Base texture
  17002. newTexture.hasAlpha = this.hasAlpha;
  17003. newTexture.level = this.level;
  17004. // Mirror Texture
  17005. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17006. newTexture.renderList = this.renderList.slice(0);
  17007. return newTexture;
  17008. };
  17009. return MirrorTexture;
  17010. })(BABYLON.RenderTargetTexture);
  17011. BABYLON.MirrorTexture = MirrorTexture;
  17012. })(BABYLON || (BABYLON = {}));
  17013. var BABYLON;
  17014. (function (BABYLON) {
  17015. var DynamicTexture = (function (_super) {
  17016. __extends(DynamicTexture, _super);
  17017. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17019. _super.call(this, null, scene, !generateMipMaps);
  17020. this.name = name;
  17021. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17022. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17023. this._generateMipMaps = generateMipMaps;
  17024. if (options.getContext) {
  17025. this._canvas = options;
  17026. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17027. }
  17028. else {
  17029. this._canvas = document.createElement("canvas");
  17030. if (options.width) {
  17031. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17032. }
  17033. else {
  17034. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17035. }
  17036. }
  17037. var textureSize = this.getSize();
  17038. this._canvas.width = textureSize.width;
  17039. this._canvas.height = textureSize.height;
  17040. this._context = this._canvas.getContext("2d");
  17041. }
  17042. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17043. get: function () {
  17044. return true;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. DynamicTexture.prototype.scale = function (ratio) {
  17050. var textureSize = this.getSize();
  17051. textureSize.width *= ratio;
  17052. textureSize.height *= ratio;
  17053. this._canvas.width = textureSize.width;
  17054. this._canvas.height = textureSize.height;
  17055. this.releaseInternalTexture();
  17056. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17057. };
  17058. DynamicTexture.prototype.getContext = function () {
  17059. return this._context;
  17060. };
  17061. DynamicTexture.prototype.clear = function () {
  17062. var size = this.getSize();
  17063. this._context.fillRect(0, 0, size.width, size.height);
  17064. };
  17065. DynamicTexture.prototype.update = function (invertY) {
  17066. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17067. };
  17068. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17069. if (update === void 0) { update = true; }
  17070. var size = this.getSize();
  17071. if (clearColor) {
  17072. this._context.fillStyle = clearColor;
  17073. this._context.fillRect(0, 0, size.width, size.height);
  17074. }
  17075. this._context.font = font;
  17076. if (x === null) {
  17077. var textSize = this._context.measureText(text);
  17078. x = (size.width - textSize.width) / 2;
  17079. }
  17080. this._context.fillStyle = color;
  17081. this._context.fillText(text, x, y);
  17082. if (update) {
  17083. this.update(invertY);
  17084. }
  17085. };
  17086. DynamicTexture.prototype.clone = function () {
  17087. var textureSize = this.getSize();
  17088. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17089. // Base texture
  17090. newTexture.hasAlpha = this.hasAlpha;
  17091. newTexture.level = this.level;
  17092. // Dynamic Texture
  17093. newTexture.wrapU = this.wrapU;
  17094. newTexture.wrapV = this.wrapV;
  17095. return newTexture;
  17096. };
  17097. return DynamicTexture;
  17098. })(BABYLON.Texture);
  17099. BABYLON.DynamicTexture = DynamicTexture;
  17100. })(BABYLON || (BABYLON = {}));
  17101. var BABYLON;
  17102. (function (BABYLON) {
  17103. var VideoTexture = (function (_super) {
  17104. __extends(VideoTexture, _super);
  17105. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17106. var _this = this;
  17107. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17108. if (invertY === void 0) { invertY = false; }
  17109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17110. _super.call(this, null, scene, !generateMipMaps, invertY);
  17111. this._autoLaunch = true;
  17112. this.name = name;
  17113. this.video = document.createElement("video");
  17114. this.video.autoplay = false;
  17115. this.video.loop = true;
  17116. this.video.addEventListener("canplaythrough", function () {
  17117. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17118. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17119. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17120. }
  17121. else {
  17122. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17123. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17124. generateMipMaps = false;
  17125. }
  17126. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17127. _this._texture.isReady = true;
  17128. });
  17129. urls.forEach(function (url) {
  17130. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17131. var source = document.createElement("source");
  17132. source.src = url;
  17133. _this.video.appendChild(source);
  17134. });
  17135. this._lastUpdate = BABYLON.Tools.Now;
  17136. }
  17137. VideoTexture.prototype.update = function () {
  17138. if (this._autoLaunch) {
  17139. this._autoLaunch = false;
  17140. this.video.play();
  17141. }
  17142. var now = BABYLON.Tools.Now;
  17143. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17144. return false;
  17145. }
  17146. this._lastUpdate = now;
  17147. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17148. return true;
  17149. };
  17150. return VideoTexture;
  17151. })(BABYLON.Texture);
  17152. BABYLON.VideoTexture = VideoTexture;
  17153. })(BABYLON || (BABYLON = {}));
  17154. var BABYLON;
  17155. (function (BABYLON) {
  17156. var CustomProceduralTexture = (function (_super) {
  17157. __extends(CustomProceduralTexture, _super);
  17158. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17159. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17160. this._animate = true;
  17161. this._time = 0;
  17162. this._texturePath = texturePath;
  17163. //Try to load json
  17164. this.loadJson(texturePath);
  17165. this.refreshRate = 1;
  17166. }
  17167. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17168. var _this = this;
  17169. var that = this;
  17170. function noConfigFile() {
  17171. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17172. try {
  17173. that.setFragment(that._texturePath);
  17174. }
  17175. catch (ex) {
  17176. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17177. }
  17178. }
  17179. var configFileUrl = jsonUrl + "/config.json";
  17180. var xhr = new XMLHttpRequest();
  17181. xhr.open("GET", configFileUrl, true);
  17182. xhr.addEventListener("load", function () {
  17183. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17184. try {
  17185. _this._config = JSON.parse(xhr.response);
  17186. _this.updateShaderUniforms();
  17187. _this.updateTextures();
  17188. _this.setFragment(_this._texturePath + "/custom");
  17189. _this._animate = _this._config.animate;
  17190. _this.refreshRate = _this._config.refreshrate;
  17191. }
  17192. catch (ex) {
  17193. noConfigFile();
  17194. }
  17195. }
  17196. else {
  17197. noConfigFile();
  17198. }
  17199. }, false);
  17200. xhr.addEventListener("error", function () {
  17201. noConfigFile();
  17202. }, false);
  17203. try {
  17204. xhr.send();
  17205. }
  17206. catch (ex) {
  17207. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17208. }
  17209. };
  17210. CustomProceduralTexture.prototype.isReady = function () {
  17211. if (!_super.prototype.isReady.call(this)) {
  17212. return false;
  17213. }
  17214. for (var name in this._textures) {
  17215. var texture = this._textures[name];
  17216. if (!texture.isReady()) {
  17217. return false;
  17218. }
  17219. }
  17220. return true;
  17221. };
  17222. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17223. if (this._animate) {
  17224. this._time += this.getScene().getAnimationRatio() * 0.03;
  17225. this.updateShaderUniforms();
  17226. }
  17227. _super.prototype.render.call(this, useCameraPostProcess);
  17228. };
  17229. CustomProceduralTexture.prototype.updateTextures = function () {
  17230. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17231. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17232. }
  17233. };
  17234. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17235. if (this._config) {
  17236. for (var j = 0; j < this._config.uniforms.length; j++) {
  17237. var uniform = this._config.uniforms[j];
  17238. switch (uniform.type) {
  17239. case "float":
  17240. this.setFloat(uniform.name, uniform.value);
  17241. break;
  17242. case "color3":
  17243. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17244. break;
  17245. case "color4":
  17246. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17247. break;
  17248. case "vector2":
  17249. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17250. break;
  17251. case "vector3":
  17252. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17253. break;
  17254. }
  17255. }
  17256. }
  17257. this.setFloat("time", this._time);
  17258. };
  17259. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17260. get: function () {
  17261. return this._animate;
  17262. },
  17263. set: function (value) {
  17264. this._animate = value;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. return CustomProceduralTexture;
  17270. })(BABYLON.ProceduralTexture);
  17271. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17272. })(BABYLON || (BABYLON = {}));
  17273. var BABYLON;
  17274. (function (BABYLON) {
  17275. var WoodProceduralTexture = (function (_super) {
  17276. __extends(WoodProceduralTexture, _super);
  17277. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17278. _super.call(this, name, size, "woodtexture", scene, fallbackTexture, generateMipMaps);
  17279. this._ampScale = 100.0;
  17280. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17281. this.updateShaderUniforms();
  17282. this.refreshRate = 0;
  17283. }
  17284. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17285. this.setFloat("ampScale", this._ampScale);
  17286. this.setColor3("woodColor", this._woodColor);
  17287. };
  17288. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17289. get: function () {
  17290. return this._ampScale;
  17291. },
  17292. set: function (value) {
  17293. this._ampScale = value;
  17294. this.updateShaderUniforms();
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17300. get: function () {
  17301. return this._woodColor;
  17302. },
  17303. set: function (value) {
  17304. this._woodColor = value;
  17305. this.updateShaderUniforms();
  17306. },
  17307. enumerable: true,
  17308. configurable: true
  17309. });
  17310. return WoodProceduralTexture;
  17311. })(BABYLON.ProceduralTexture);
  17312. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17313. var FireProceduralTexture = (function (_super) {
  17314. __extends(FireProceduralTexture, _super);
  17315. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17316. _super.call(this, name, size, "firetexture", scene, fallbackTexture, generateMipMaps);
  17317. this._time = 0.0;
  17318. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17319. this._autoGenerateTime = true;
  17320. this._alphaThreshold = 0.5;
  17321. this._fireColors = FireProceduralTexture.RedFireColors;
  17322. this.updateShaderUniforms();
  17323. this.refreshRate = 1;
  17324. }
  17325. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17326. this.setFloat("time", this._time);
  17327. this.setVector2("speed", this._speed);
  17328. this.setColor3("c1", this._fireColors[0]);
  17329. this.setColor3("c2", this._fireColors[1]);
  17330. this.setColor3("c3", this._fireColors[2]);
  17331. this.setColor3("c4", this._fireColors[3]);
  17332. this.setColor3("c5", this._fireColors[4]);
  17333. this.setColor3("c6", this._fireColors[5]);
  17334. this.setFloat("alphaThreshold", this._alphaThreshold);
  17335. };
  17336. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17337. if (this._autoGenerateTime) {
  17338. this._time += this.getScene().getAnimationRatio() * 0.03;
  17339. this.updateShaderUniforms();
  17340. }
  17341. _super.prototype.render.call(this, useCameraPostProcess);
  17342. };
  17343. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17344. get: function () {
  17345. return [
  17346. new BABYLON.Color3(0.5, 0.0, 1.0),
  17347. new BABYLON.Color3(0.9, 0.0, 1.0),
  17348. new BABYLON.Color3(0.2, 0.0, 1.0),
  17349. new BABYLON.Color3(1.0, 0.9, 1.0),
  17350. new BABYLON.Color3(0.1, 0.1, 1.0),
  17351. new BABYLON.Color3(0.9, 0.9, 1.0)
  17352. ];
  17353. },
  17354. enumerable: true,
  17355. configurable: true
  17356. });
  17357. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17358. get: function () {
  17359. return [
  17360. new BABYLON.Color3(0.5, 1.0, 0.0),
  17361. new BABYLON.Color3(0.5, 1.0, 0.0),
  17362. new BABYLON.Color3(0.3, 0.4, 0.0),
  17363. new BABYLON.Color3(0.5, 1.0, 0.0),
  17364. new BABYLON.Color3(0.2, 0.0, 0.0),
  17365. new BABYLON.Color3(0.5, 1.0, 0.0)
  17366. ];
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17372. get: function () {
  17373. return [
  17374. new BABYLON.Color3(0.5, 0.0, 0.1),
  17375. new BABYLON.Color3(0.9, 0.0, 0.0),
  17376. new BABYLON.Color3(0.2, 0.0, 0.0),
  17377. new BABYLON.Color3(1.0, 0.9, 0.0),
  17378. new BABYLON.Color3(0.1, 0.1, 0.1),
  17379. new BABYLON.Color3(0.9, 0.9, 0.9)
  17380. ];
  17381. },
  17382. enumerable: true,
  17383. configurable: true
  17384. });
  17385. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17386. get: function () {
  17387. return [
  17388. new BABYLON.Color3(0.1, 0.0, 0.5),
  17389. new BABYLON.Color3(0.0, 0.0, 0.5),
  17390. new BABYLON.Color3(0.1, 0.0, 0.2),
  17391. new BABYLON.Color3(0.0, 0.0, 1.0),
  17392. new BABYLON.Color3(0.1, 0.2, 0.3),
  17393. new BABYLON.Color3(0.0, 0.2, 0.9)
  17394. ];
  17395. },
  17396. enumerable: true,
  17397. configurable: true
  17398. });
  17399. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17400. get: function () {
  17401. return this._fireColors;
  17402. },
  17403. set: function (value) {
  17404. this._fireColors = value;
  17405. this.updateShaderUniforms();
  17406. },
  17407. enumerable: true,
  17408. configurable: true
  17409. });
  17410. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17411. get: function () {
  17412. return this._time;
  17413. },
  17414. set: function (value) {
  17415. this._time = value;
  17416. this.updateShaderUniforms();
  17417. },
  17418. enumerable: true,
  17419. configurable: true
  17420. });
  17421. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17422. get: function () {
  17423. return this._speed;
  17424. },
  17425. set: function (value) {
  17426. this._speed = value;
  17427. this.updateShaderUniforms();
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17433. get: function () {
  17434. return this._alphaThreshold;
  17435. },
  17436. set: function (value) {
  17437. this._alphaThreshold = value;
  17438. this.updateShaderUniforms();
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. return FireProceduralTexture;
  17444. })(BABYLON.ProceduralTexture);
  17445. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17446. var CloudProceduralTexture = (function (_super) {
  17447. __extends(CloudProceduralTexture, _super);
  17448. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17449. _super.call(this, name, size, "cloudtexture", scene, fallbackTexture, generateMipMaps);
  17450. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17451. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17452. this.updateShaderUniforms();
  17453. this.refreshRate = 0;
  17454. }
  17455. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17456. this.setColor4("skyColor", this._skyColor);
  17457. this.setColor4("cloudColor", this._cloudColor);
  17458. };
  17459. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17460. get: function () {
  17461. return this._skyColor;
  17462. },
  17463. set: function (value) {
  17464. this._skyColor = value;
  17465. this.updateShaderUniforms();
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17471. get: function () {
  17472. return this._cloudColor;
  17473. },
  17474. set: function (value) {
  17475. this._cloudColor = value;
  17476. this.updateShaderUniforms();
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. return CloudProceduralTexture;
  17482. })(BABYLON.ProceduralTexture);
  17483. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17484. var GrassProceduralTexture = (function (_super) {
  17485. __extends(GrassProceduralTexture, _super);
  17486. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17487. _super.call(this, name, size, "grasstexture", scene, fallbackTexture, generateMipMaps);
  17488. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17489. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17490. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17491. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17492. this._grassColors = [
  17493. new BABYLON.Color3(0.29, 0.38, 0.02),
  17494. new BABYLON.Color3(0.36, 0.49, 0.09),
  17495. new BABYLON.Color3(0.51, 0.6, 0.28)
  17496. ];
  17497. this.updateShaderUniforms();
  17498. this.refreshRate = 0;
  17499. }
  17500. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17501. this.setColor3("herb1Color", this._grassColors[0]);
  17502. this.setColor3("herb2Color", this._grassColors[1]);
  17503. this.setColor3("herb3Color", this._grassColors[2]);
  17504. this.setColor3("groundColor", this._groundColor);
  17505. };
  17506. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17507. get: function () {
  17508. return this._grassColors;
  17509. },
  17510. set: function (value) {
  17511. this._grassColors = value;
  17512. this.updateShaderUniforms();
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17518. get: function () {
  17519. return this._groundColor;
  17520. },
  17521. set: function (value) {
  17522. this.groundColor = value;
  17523. this.updateShaderUniforms();
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. return GrassProceduralTexture;
  17529. })(BABYLON.ProceduralTexture);
  17530. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17531. var RoadProceduralTexture = (function (_super) {
  17532. __extends(RoadProceduralTexture, _super);
  17533. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17534. _super.call(this, name, size, "roadtexture", scene, fallbackTexture, generateMipMaps);
  17535. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17536. this.updateShaderUniforms();
  17537. this.refreshRate = 0;
  17538. }
  17539. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17540. this.setColor3("roadColor", this._roadColor);
  17541. };
  17542. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17543. get: function () {
  17544. return this._roadColor;
  17545. },
  17546. set: function (value) {
  17547. this._roadColor = value;
  17548. this.updateShaderUniforms();
  17549. },
  17550. enumerable: true,
  17551. configurable: true
  17552. });
  17553. return RoadProceduralTexture;
  17554. })(BABYLON.ProceduralTexture);
  17555. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17556. var BrickProceduralTexture = (function (_super) {
  17557. __extends(BrickProceduralTexture, _super);
  17558. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17559. _super.call(this, name, size, "bricktexture", scene, fallbackTexture, generateMipMaps);
  17560. this._numberOfBricksHeight = 15;
  17561. this._numberOfBricksWidth = 5;
  17562. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17563. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17564. this.updateShaderUniforms();
  17565. this.refreshRate = 0;
  17566. }
  17567. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17568. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17569. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17570. this.setColor3("brickColor", this._brickColor);
  17571. this.setColor3("jointColor", this._jointColor);
  17572. };
  17573. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17574. get: function () {
  17575. return this._numberOfBricksHeight;
  17576. },
  17577. set: function (value) {
  17578. this._numberOfBricksHeight = value;
  17579. this.updateShaderUniforms();
  17580. },
  17581. enumerable: true,
  17582. configurable: true
  17583. });
  17584. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17585. get: function () {
  17586. return this._numberOfBricksWidth;
  17587. },
  17588. set: function (value) {
  17589. this._numberOfBricksWidth = value;
  17590. this.updateShaderUniforms();
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17596. get: function () {
  17597. return this._jointColor;
  17598. },
  17599. set: function (value) {
  17600. this._jointColor = value;
  17601. this.updateShaderUniforms();
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17607. get: function () {
  17608. return this._brickColor;
  17609. },
  17610. set: function (value) {
  17611. this._brickColor = value;
  17612. this.updateShaderUniforms();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. return BrickProceduralTexture;
  17618. })(BABYLON.ProceduralTexture);
  17619. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17620. var MarbleProceduralTexture = (function (_super) {
  17621. __extends(MarbleProceduralTexture, _super);
  17622. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17623. _super.call(this, name, size, "marbletexture", scene, fallbackTexture, generateMipMaps);
  17624. this._numberOfTilesHeight = 3;
  17625. this._numberOfTilesWidth = 3;
  17626. this._amplitude = 9.0;
  17627. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17628. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17629. this.updateShaderUniforms();
  17630. this.refreshRate = 0;
  17631. }
  17632. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17633. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17634. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17635. this.setFloat("amplitude", this._amplitude);
  17636. this.setColor3("marbleColor", this._marbleColor);
  17637. this.setColor3("jointColor", this._jointColor);
  17638. };
  17639. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17640. get: function () {
  17641. return this._numberOfTilesHeight;
  17642. },
  17643. set: function (value) {
  17644. this._numberOfTilesHeight = value;
  17645. this.updateShaderUniforms();
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17651. get: function () {
  17652. return this._numberOfTilesWidth;
  17653. },
  17654. set: function (value) {
  17655. this._numberOfTilesWidth = value;
  17656. this.updateShaderUniforms();
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17662. get: function () {
  17663. return this._jointColor;
  17664. },
  17665. set: function (value) {
  17666. this._jointColor = value;
  17667. this.updateShaderUniforms();
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17673. get: function () {
  17674. return this._marbleColor;
  17675. },
  17676. set: function (value) {
  17677. this._marbleColor = value;
  17678. this.updateShaderUniforms();
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. return MarbleProceduralTexture;
  17684. })(BABYLON.ProceduralTexture);
  17685. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17686. })(BABYLON || (BABYLON = {}));
  17687. var BABYLON;
  17688. (function (BABYLON) {
  17689. var EffectFallbacks = (function () {
  17690. function EffectFallbacks() {
  17691. this._defines = {};
  17692. this._currentRank = 32;
  17693. this._maxRank = -1;
  17694. }
  17695. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17696. if (!this._defines[rank]) {
  17697. if (rank < this._currentRank) {
  17698. this._currentRank = rank;
  17699. }
  17700. if (rank > this._maxRank) {
  17701. this._maxRank = rank;
  17702. }
  17703. this._defines[rank] = new Array();
  17704. }
  17705. this._defines[rank].push(define);
  17706. };
  17707. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17708. this._meshRank = rank;
  17709. this._mesh = mesh;
  17710. if (rank > this._maxRank) {
  17711. this._maxRank = rank;
  17712. }
  17713. };
  17714. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17715. get: function () {
  17716. return this._currentRank <= this._maxRank;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17722. var currentFallbacks = this._defines[this._currentRank];
  17723. for (var index = 0; index < currentFallbacks.length; index++) {
  17724. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17725. }
  17726. if (this._mesh && this._currentRank === this._meshRank) {
  17727. this._mesh.computeBonesUsingShaders = false;
  17728. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17729. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17730. }
  17731. this._currentRank++;
  17732. return currentDefines;
  17733. };
  17734. return EffectFallbacks;
  17735. })();
  17736. BABYLON.EffectFallbacks = EffectFallbacks;
  17737. var Effect = (function () {
  17738. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17739. var _this = this;
  17740. this._isReady = false;
  17741. this._compilationError = "";
  17742. this._valueCache = [];
  17743. this._engine = engine;
  17744. this.name = baseName;
  17745. this.defines = defines;
  17746. this._uniformsNames = uniformsNames.concat(samplers);
  17747. this._samplers = samplers;
  17748. this._attributesNames = attributesNames;
  17749. this.onError = onError;
  17750. this.onCompiled = onCompiled;
  17751. var vertexSource;
  17752. var fragmentSource;
  17753. if (baseName.vertexElement) {
  17754. vertexSource = document.getElementById(baseName.vertexElement);
  17755. if (!vertexSource) {
  17756. vertexSource = baseName.vertexElement;
  17757. }
  17758. }
  17759. else {
  17760. vertexSource = baseName.vertex || baseName;
  17761. }
  17762. if (baseName.fragmentElement) {
  17763. fragmentSource = document.getElementById(baseName.fragmentElement);
  17764. if (!fragmentSource) {
  17765. fragmentSource = baseName.fragmentElement;
  17766. }
  17767. }
  17768. else {
  17769. fragmentSource = baseName.fragment || baseName;
  17770. }
  17771. this._loadVertexShader(vertexSource, function (vertexCode) {
  17772. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17773. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17774. });
  17775. });
  17776. }
  17777. // Properties
  17778. Effect.prototype.isReady = function () {
  17779. return this._isReady;
  17780. };
  17781. Effect.prototype.getProgram = function () {
  17782. return this._program;
  17783. };
  17784. Effect.prototype.getAttributesNames = function () {
  17785. return this._attributesNames;
  17786. };
  17787. Effect.prototype.getAttributeLocation = function (index) {
  17788. return this._attributes[index];
  17789. };
  17790. Effect.prototype.getAttributeLocationByName = function (name) {
  17791. var index = this._attributesNames.indexOf(name);
  17792. return this._attributes[index];
  17793. };
  17794. Effect.prototype.getAttributesCount = function () {
  17795. return this._attributes.length;
  17796. };
  17797. Effect.prototype.getUniformIndex = function (uniformName) {
  17798. return this._uniformsNames.indexOf(uniformName);
  17799. };
  17800. Effect.prototype.getUniform = function (uniformName) {
  17801. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17802. };
  17803. Effect.prototype.getSamplers = function () {
  17804. return this._samplers;
  17805. };
  17806. Effect.prototype.getCompilationError = function () {
  17807. return this._compilationError;
  17808. };
  17809. // Methods
  17810. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17811. // DOM element ?
  17812. if (vertex instanceof HTMLElement) {
  17813. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17814. callback(vertexCode);
  17815. return;
  17816. }
  17817. // Is in local store ?
  17818. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17819. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17820. return;
  17821. }
  17822. var vertexShaderUrl;
  17823. if (vertex[0] === "." || vertex[0] === "/") {
  17824. vertexShaderUrl = vertex;
  17825. }
  17826. else {
  17827. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17828. }
  17829. // Vertex shader
  17830. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17831. };
  17832. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17833. // DOM element ?
  17834. if (fragment instanceof HTMLElement) {
  17835. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17836. callback(fragmentCode);
  17837. return;
  17838. }
  17839. // Is in local store ?
  17840. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17841. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17842. return;
  17843. }
  17844. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17845. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17846. return;
  17847. }
  17848. var fragmentShaderUrl;
  17849. if (fragment[0] === "." || fragment[0] === "/") {
  17850. fragmentShaderUrl = fragment;
  17851. }
  17852. else {
  17853. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17854. }
  17855. // Fragment shader
  17856. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17857. };
  17858. Effect.prototype._dumpShadersName = function () {
  17859. if (this.name.vertexElement) {
  17860. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17861. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17862. }
  17863. else if (this.name.vertex) {
  17864. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17865. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17866. }
  17867. else {
  17868. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17869. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17870. }
  17871. };
  17872. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17873. try {
  17874. var engine = this._engine;
  17875. if (!engine.getCaps().highPrecisionShaderSupported) {
  17876. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17877. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17878. }
  17879. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17880. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17881. this._attributes = engine.getAttributes(this._program, attributesNames);
  17882. for (var index = 0; index < this._samplers.length; index++) {
  17883. var sampler = this.getUniform(this._samplers[index]);
  17884. if (sampler == null) {
  17885. this._samplers.splice(index, 1);
  17886. index--;
  17887. }
  17888. }
  17889. engine.bindSamplers(this);
  17890. this._isReady = true;
  17891. if (this.onCompiled) {
  17892. this.onCompiled(this);
  17893. }
  17894. }
  17895. catch (e) {
  17896. // Is it a problem with precision?
  17897. if (e.message.indexOf("highp") !== -1) {
  17898. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17899. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17900. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17901. return;
  17902. }
  17903. // Let's go through fallbacks then
  17904. if (fallbacks && fallbacks.isMoreFallbacks) {
  17905. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17906. this._dumpShadersName();
  17907. defines = fallbacks.reduce(defines);
  17908. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17909. }
  17910. else {
  17911. BABYLON.Tools.Error("Unable to compile effect: ");
  17912. this._dumpShadersName();
  17913. BABYLON.Tools.Error("Defines: " + defines);
  17914. BABYLON.Tools.Error("Error: " + e.message);
  17915. this._compilationError = e.message;
  17916. if (this.onError) {
  17917. this.onError(this, this._compilationError);
  17918. }
  17919. }
  17920. }
  17921. };
  17922. Object.defineProperty(Effect.prototype, "isSupported", {
  17923. get: function () {
  17924. return this._compilationError === "";
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Effect.prototype._bindTexture = function (channel, texture) {
  17930. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17931. };
  17932. Effect.prototype.setTexture = function (channel, texture) {
  17933. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17934. };
  17935. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17936. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17937. };
  17938. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17939. if (!this._valueCache[uniformName]) {
  17940. this._valueCache[uniformName] = new BABYLON.Matrix();
  17941. }
  17942. for (var index = 0; index < 16; index++) {
  17943. this._valueCache[uniformName].m[index] = matrix.m[index];
  17944. }
  17945. };
  17946. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17947. if (!this._valueCache[uniformName]) {
  17948. this._valueCache[uniformName] = [x, y];
  17949. return;
  17950. }
  17951. this._valueCache[uniformName][0] = x;
  17952. this._valueCache[uniformName][1] = y;
  17953. };
  17954. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17955. if (!this._valueCache[uniformName]) {
  17956. this._valueCache[uniformName] = [x, y, z];
  17957. return;
  17958. }
  17959. this._valueCache[uniformName][0] = x;
  17960. this._valueCache[uniformName][1] = y;
  17961. this._valueCache[uniformName][2] = z;
  17962. };
  17963. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17964. if (!this._valueCache[uniformName]) {
  17965. this._valueCache[uniformName] = [x, y, z, w];
  17966. return;
  17967. }
  17968. this._valueCache[uniformName][0] = x;
  17969. this._valueCache[uniformName][1] = y;
  17970. this._valueCache[uniformName][2] = z;
  17971. this._valueCache[uniformName][3] = w;
  17972. };
  17973. Effect.prototype.setArray = function (uniformName, array) {
  17974. this._engine.setArray(this.getUniform(uniformName), array);
  17975. return this;
  17976. };
  17977. Effect.prototype.setArray2 = function (uniformName, array) {
  17978. this._engine.setArray2(this.getUniform(uniformName), array);
  17979. return this;
  17980. };
  17981. Effect.prototype.setArray3 = function (uniformName, array) {
  17982. this._engine.setArray3(this.getUniform(uniformName), array);
  17983. return this;
  17984. };
  17985. Effect.prototype.setArray4 = function (uniformName, array) {
  17986. this._engine.setArray4(this.getUniform(uniformName), array);
  17987. return this;
  17988. };
  17989. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17990. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17991. return this;
  17992. };
  17993. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17994. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17995. return this;
  17996. this._cacheMatrix(uniformName, matrix);
  17997. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17998. return this;
  17999. };
  18000. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18001. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18002. return this;
  18003. };
  18004. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18005. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18006. return this;
  18007. };
  18008. Effect.prototype.setFloat = function (uniformName, value) {
  18009. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18010. return this;
  18011. this._valueCache[uniformName] = value;
  18012. this._engine.setFloat(this.getUniform(uniformName), value);
  18013. return this;
  18014. };
  18015. Effect.prototype.setBool = function (uniformName, bool) {
  18016. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18017. return this;
  18018. this._valueCache[uniformName] = bool;
  18019. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18020. return this;
  18021. };
  18022. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18023. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18024. return this;
  18025. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18026. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18027. return this;
  18028. };
  18029. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18030. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18031. return this;
  18032. this._cacheFloat2(uniformName, x, y);
  18033. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18034. return this;
  18035. };
  18036. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18037. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18038. return this;
  18039. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18040. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18041. return this;
  18042. };
  18043. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18044. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18045. return this;
  18046. this._cacheFloat3(uniformName, x, y, z);
  18047. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18048. return this;
  18049. };
  18050. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18051. 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)
  18052. return this;
  18053. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18054. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18055. return this;
  18056. };
  18057. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18058. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18059. return this;
  18060. this._cacheFloat4(uniformName, x, y, z, w);
  18061. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18062. return this;
  18063. };
  18064. Effect.prototype.setColor3 = function (uniformName, color3) {
  18065. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18066. return this;
  18067. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18068. this._engine.setColor3(this.getUniform(uniformName), color3);
  18069. return this;
  18070. };
  18071. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18072. 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)
  18073. return this;
  18074. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18075. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18076. return this;
  18077. };
  18078. // Statics
  18079. Effect.ShadersStore = {};
  18080. return Effect;
  18081. })();
  18082. BABYLON.Effect = Effect;
  18083. })(BABYLON || (BABYLON = {}));
  18084. var BABYLON;
  18085. (function (BABYLON) {
  18086. var MaterialDefines = (function () {
  18087. function MaterialDefines() {
  18088. }
  18089. MaterialDefines.prototype.isEqual = function (other) {
  18090. for (var index = 0; index < this._keys.length; index++) {
  18091. var prop = this._keys[index];
  18092. if (this[prop] !== other[prop]) {
  18093. return false;
  18094. }
  18095. }
  18096. return true;
  18097. };
  18098. MaterialDefines.prototype.cloneTo = function (other) {
  18099. for (var index = 0; index < this._keys.length; index++) {
  18100. var prop = this._keys[index];
  18101. other[prop] = this[prop];
  18102. }
  18103. };
  18104. MaterialDefines.prototype.reset = function () {
  18105. for (var index = 0; index < this._keys.length; index++) {
  18106. var prop = this._keys[index];
  18107. if (typeof (this[prop]) === "number") {
  18108. this[prop] = 0;
  18109. }
  18110. else {
  18111. this[prop] = false;
  18112. }
  18113. }
  18114. };
  18115. MaterialDefines.prototype.toString = function () {
  18116. var result = "";
  18117. for (var index = 0; index < this._keys.length; index++) {
  18118. var prop = this._keys[index];
  18119. if (typeof (this[prop]) === "number") {
  18120. result += "#define " + prop + " " + this[prop] + "\n";
  18121. }
  18122. else if (this[prop]) {
  18123. result += "#define " + prop + "\n";
  18124. }
  18125. }
  18126. return result;
  18127. };
  18128. return MaterialDefines;
  18129. })();
  18130. BABYLON.MaterialDefines = MaterialDefines;
  18131. var Material = (function () {
  18132. function Material(name, scene, doNotAdd) {
  18133. this.name = name;
  18134. this.checkReadyOnEveryCall = false;
  18135. this.checkReadyOnlyOnce = false;
  18136. this.state = "";
  18137. this.alpha = 1.0;
  18138. this.backFaceCulling = true;
  18139. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18140. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18141. this.disableDepthWrite = false;
  18142. this.fogEnabled = true;
  18143. this._wasPreviouslyReady = false;
  18144. this._fillMode = Material.TriangleFillMode;
  18145. this.pointSize = 1.0;
  18146. this.zOffset = 0;
  18147. this.id = name;
  18148. this._scene = scene;
  18149. if (!doNotAdd) {
  18150. scene.materials.push(this);
  18151. }
  18152. }
  18153. Object.defineProperty(Material, "TriangleFillMode", {
  18154. get: function () {
  18155. return Material._TriangleFillMode;
  18156. },
  18157. enumerable: true,
  18158. configurable: true
  18159. });
  18160. Object.defineProperty(Material, "WireFrameFillMode", {
  18161. get: function () {
  18162. return Material._WireFrameFillMode;
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(Material, "PointFillMode", {
  18168. get: function () {
  18169. return Material._PointFillMode;
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18175. get: function () {
  18176. return Material._ClockWiseSideOrientation;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18182. get: function () {
  18183. return Material._CounterClockWiseSideOrientation;
  18184. },
  18185. enumerable: true,
  18186. configurable: true
  18187. });
  18188. Object.defineProperty(Material.prototype, "wireframe", {
  18189. get: function () {
  18190. return this._fillMode === Material.WireFrameFillMode;
  18191. },
  18192. set: function (value) {
  18193. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18194. },
  18195. enumerable: true,
  18196. configurable: true
  18197. });
  18198. Object.defineProperty(Material.prototype, "pointsCloud", {
  18199. get: function () {
  18200. return this._fillMode === Material.PointFillMode;
  18201. },
  18202. set: function (value) {
  18203. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. Object.defineProperty(Material.prototype, "fillMode", {
  18209. get: function () {
  18210. return this._fillMode;
  18211. },
  18212. set: function (value) {
  18213. this._fillMode = value;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. Material.prototype.isReady = function (mesh, useInstances) {
  18219. return true;
  18220. };
  18221. Material.prototype.getEffect = function () {
  18222. return this._effect;
  18223. };
  18224. Material.prototype.getScene = function () {
  18225. return this._scene;
  18226. };
  18227. Material.prototype.needAlphaBlending = function () {
  18228. return (this.alpha < 1.0);
  18229. };
  18230. Material.prototype.needAlphaTesting = function () {
  18231. return false;
  18232. };
  18233. Material.prototype.getAlphaTestTexture = function () {
  18234. return null;
  18235. };
  18236. Material.prototype.trackCreation = function (onCompiled, onError) {
  18237. };
  18238. Material.prototype.markDirty = function () {
  18239. this._wasPreviouslyReady = false;
  18240. };
  18241. Material.prototype._preBind = function () {
  18242. var engine = this._scene.getEngine();
  18243. engine.enableEffect(this._effect);
  18244. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18245. };
  18246. Material.prototype.bind = function (world, mesh) {
  18247. this._scene._cachedMaterial = this;
  18248. if (this.onBind) {
  18249. this.onBind(this, mesh);
  18250. }
  18251. if (this.disableDepthWrite) {
  18252. var engine = this._scene.getEngine();
  18253. this._cachedDepthWriteState = engine.getDepthWrite();
  18254. engine.setDepthWrite(false);
  18255. }
  18256. };
  18257. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18258. };
  18259. Material.prototype.unbind = function () {
  18260. if (this.disableDepthWrite) {
  18261. var engine = this._scene.getEngine();
  18262. engine.setDepthWrite(this._cachedDepthWriteState);
  18263. }
  18264. };
  18265. Material.prototype.clone = function (name) {
  18266. return null;
  18267. };
  18268. Material.prototype.getBindedMeshes = function () {
  18269. var result = new Array();
  18270. for (var index = 0; index < this._scene.meshes.length; index++) {
  18271. var mesh = this._scene.meshes[index];
  18272. if (mesh.material === this) {
  18273. result.push(mesh);
  18274. }
  18275. }
  18276. return result;
  18277. };
  18278. Material.prototype.dispose = function (forceDisposeEffect) {
  18279. // Animations
  18280. this.getScene().stopAnimation(this);
  18281. // Remove from scene
  18282. var index = this._scene.materials.indexOf(this);
  18283. if (index >= 0) {
  18284. this._scene.materials.splice(index, 1);
  18285. }
  18286. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18287. if (forceDisposeEffect && this._effect) {
  18288. this._scene.getEngine()._releaseEffect(this._effect);
  18289. this._effect = null;
  18290. }
  18291. // Remove from meshes
  18292. for (index = 0; index < this._scene.meshes.length; index++) {
  18293. var mesh = this._scene.meshes[index];
  18294. if (mesh.material === this) {
  18295. mesh.material = null;
  18296. }
  18297. }
  18298. // Callback
  18299. if (this.onDispose) {
  18300. this.onDispose();
  18301. }
  18302. };
  18303. Material.prototype.copyTo = function (other) {
  18304. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18305. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18306. other.alpha = this.alpha;
  18307. other.fillMode = this.fillMode;
  18308. other.backFaceCulling = this.backFaceCulling;
  18309. other.wireframe = this.wireframe;
  18310. other.fogEnabled = this.fogEnabled;
  18311. other.wireframe = this.wireframe;
  18312. other.zOffset = this.zOffset;
  18313. other.alphaMode = this.alphaMode;
  18314. other.sideOrientation = this.sideOrientation;
  18315. other.disableDepthWrite = this.disableDepthWrite;
  18316. other.pointSize = this.pointSize;
  18317. other.pointsCloud = this.pointsCloud;
  18318. };
  18319. Material._TriangleFillMode = 0;
  18320. Material._WireFrameFillMode = 1;
  18321. Material._PointFillMode = 2;
  18322. Material._ClockWiseSideOrientation = 0;
  18323. Material._CounterClockWiseSideOrientation = 1;
  18324. return Material;
  18325. })();
  18326. BABYLON.Material = Material;
  18327. })(BABYLON || (BABYLON = {}));
  18328. var BABYLON;
  18329. (function (BABYLON) {
  18330. var maxSimultaneousLights = 4;
  18331. var FresnelParameters = (function () {
  18332. function FresnelParameters() {
  18333. this.isEnabled = true;
  18334. this.leftColor = BABYLON.Color3.White();
  18335. this.rightColor = BABYLON.Color3.Black();
  18336. this.bias = 0;
  18337. this.power = 1;
  18338. }
  18339. FresnelParameters.prototype.clone = function () {
  18340. var newFresnelParameters = new FresnelParameters();
  18341. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18342. return new FresnelParameters;
  18343. };
  18344. return FresnelParameters;
  18345. })();
  18346. BABYLON.FresnelParameters = FresnelParameters;
  18347. var StandardMaterialDefines = (function (_super) {
  18348. __extends(StandardMaterialDefines, _super);
  18349. function StandardMaterialDefines() {
  18350. _super.call(this);
  18351. this.DIFFUSE = false;
  18352. this.AMBIENT = false;
  18353. this.OPACITY = false;
  18354. this.OPACITYRGB = false;
  18355. this.REFLECTION = false;
  18356. this.EMISSIVE = false;
  18357. this.SPECULAR = false;
  18358. this.BUMP = false;
  18359. this.SPECULAROVERALPHA = false;
  18360. this.CLIPPLANE = false;
  18361. this.ALPHATEST = false;
  18362. this.ALPHAFROMDIFFUSE = false;
  18363. this.POINTSIZE = false;
  18364. this.FOG = false;
  18365. this.LIGHT0 = false;
  18366. this.LIGHT1 = false;
  18367. this.LIGHT2 = false;
  18368. this.LIGHT3 = false;
  18369. this.SPOTLIGHT0 = false;
  18370. this.SPOTLIGHT1 = false;
  18371. this.SPOTLIGHT2 = false;
  18372. this.SPOTLIGHT3 = false;
  18373. this.HEMILIGHT0 = false;
  18374. this.HEMILIGHT1 = false;
  18375. this.HEMILIGHT2 = false;
  18376. this.HEMILIGHT3 = false;
  18377. this.POINTLIGHT0 = false;
  18378. this.POINTLIGHT1 = false;
  18379. this.POINTLIGHT2 = false;
  18380. this.POINTLIGHT3 = false;
  18381. this.DIRLIGHT0 = false;
  18382. this.DIRLIGHT1 = false;
  18383. this.DIRLIGHT2 = false;
  18384. this.DIRLIGHT3 = false;
  18385. this.SPECULARTERM = false;
  18386. this.SHADOW0 = false;
  18387. this.SHADOW1 = false;
  18388. this.SHADOW2 = false;
  18389. this.SHADOW3 = false;
  18390. this.SHADOWS = false;
  18391. this.SHADOWVSM0 = false;
  18392. this.SHADOWVSM1 = false;
  18393. this.SHADOWVSM2 = false;
  18394. this.SHADOWVSM3 = false;
  18395. this.SHADOWPCF0 = false;
  18396. this.SHADOWPCF1 = false;
  18397. this.SHADOWPCF2 = false;
  18398. this.SHADOWPCF3 = false;
  18399. this.DIFFUSEFRESNEL = false;
  18400. this.OPACITYFRESNEL = false;
  18401. this.REFLECTIONFRESNEL = false;
  18402. this.EMISSIVEFRESNEL = false;
  18403. this.FRESNEL = false;
  18404. this.NORMAL = false;
  18405. this.UV1 = false;
  18406. this.UV2 = false;
  18407. this.VERTEXCOLOR = false;
  18408. this.VERTEXALPHA = false;
  18409. this.NUM_BONE_INFLUENCERS = 0;
  18410. this.BonesPerMesh = 0;
  18411. this.INSTANCES = false;
  18412. this.GLOSSINESS = false;
  18413. this.ROUGHNESS = false;
  18414. this.EMISSIVEASILLUMINATION = false;
  18415. this.LINKEMISSIVEWITHDIFFUSE = false;
  18416. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18417. this.LIGHTMAP = false;
  18418. this.USELIGHTMAPASSHADOWMAP = false;
  18419. this.REFLECTIONMAP_3D = false;
  18420. this.REFLECTIONMAP_SPHERICAL = false;
  18421. this.REFLECTIONMAP_PLANAR = false;
  18422. this.REFLECTIONMAP_CUBIC = false;
  18423. this.REFLECTIONMAP_PROJECTION = false;
  18424. this.REFLECTIONMAP_SKYBOX = false;
  18425. this.REFLECTIONMAP_EXPLICIT = false;
  18426. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18427. this.INVERTCUBICMAP = false;
  18428. this._keys = Object.keys(this);
  18429. }
  18430. return StandardMaterialDefines;
  18431. })(BABYLON.MaterialDefines);
  18432. var StandardMaterial = (function (_super) {
  18433. __extends(StandardMaterial, _super);
  18434. function StandardMaterial(name, scene) {
  18435. var _this = this;
  18436. _super.call(this, name, scene);
  18437. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18438. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18439. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18440. this.specularPower = 64;
  18441. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18442. this.useAlphaFromDiffuseTexture = false;
  18443. this.useEmissiveAsIllumination = false;
  18444. this.linkEmissiveWithDiffuse = false;
  18445. this.useReflectionFresnelFromSpecular = false;
  18446. this.useSpecularOverAlpha = true;
  18447. this.disableLighting = false;
  18448. this.roughness = 0;
  18449. this.useLightmapAsShadowmap = false;
  18450. this.useGlossinessFromSpecularMapAlpha = false;
  18451. this._renderTargets = new BABYLON.SmartArray(16);
  18452. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18453. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18454. this._defines = new StandardMaterialDefines();
  18455. this._cachedDefines = new StandardMaterialDefines();
  18456. this._cachedDefines.BonesPerMesh = -1;
  18457. this.getRenderTargetTextures = function () {
  18458. _this._renderTargets.reset();
  18459. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18460. _this._renderTargets.push(_this.reflectionTexture);
  18461. }
  18462. return _this._renderTargets;
  18463. };
  18464. }
  18465. StandardMaterial.prototype.needAlphaBlending = function () {
  18466. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18467. };
  18468. StandardMaterial.prototype.needAlphaTesting = function () {
  18469. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18470. };
  18471. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18472. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18473. };
  18474. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18475. return this.diffuseTexture;
  18476. };
  18477. // Methods
  18478. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18479. if (!mesh) {
  18480. return true;
  18481. }
  18482. if (this._defines.INSTANCES !== useInstances) {
  18483. return false;
  18484. }
  18485. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18486. return true;
  18487. }
  18488. return false;
  18489. };
  18490. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18491. var lightIndex = 0;
  18492. var needNormals = false;
  18493. for (var index = 0; index < scene.lights.length; index++) {
  18494. var light = scene.lights[index];
  18495. if (!light.isEnabled()) {
  18496. continue;
  18497. }
  18498. // Excluded check
  18499. if (light._excludedMeshesIds.length > 0) {
  18500. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18501. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18502. if (excludedMesh) {
  18503. light.excludedMeshes.push(excludedMesh);
  18504. }
  18505. }
  18506. light._excludedMeshesIds = [];
  18507. }
  18508. // Included check
  18509. if (light._includedOnlyMeshesIds.length > 0) {
  18510. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18511. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18512. if (includedOnlyMesh) {
  18513. light.includedOnlyMeshes.push(includedOnlyMesh);
  18514. }
  18515. }
  18516. light._includedOnlyMeshesIds = [];
  18517. }
  18518. if (!light.canAffectMesh(mesh)) {
  18519. continue;
  18520. }
  18521. needNormals = true;
  18522. defines["LIGHT" + lightIndex] = true;
  18523. var type;
  18524. if (light instanceof BABYLON.SpotLight) {
  18525. type = "SPOTLIGHT" + lightIndex;
  18526. }
  18527. else if (light instanceof BABYLON.HemisphericLight) {
  18528. type = "HEMILIGHT" + lightIndex;
  18529. }
  18530. else if (light instanceof BABYLON.PointLight) {
  18531. type = "POINTLIGHT" + lightIndex;
  18532. }
  18533. else {
  18534. type = "DIRLIGHT" + lightIndex;
  18535. }
  18536. defines[type] = true;
  18537. // Specular
  18538. if (!light.specular.equalsFloats(0, 0, 0)) {
  18539. defines["SPECULARTERM"] = true;
  18540. }
  18541. // Shadows
  18542. if (scene.shadowsEnabled) {
  18543. var shadowGenerator = light.getShadowGenerator();
  18544. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18545. defines["SHADOW" + lightIndex] = true;
  18546. defines["SHADOWS"] = true;
  18547. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18548. defines["SHADOWVSM" + lightIndex] = true;
  18549. }
  18550. if (shadowGenerator.usePoissonSampling) {
  18551. defines["SHADOWPCF" + lightIndex] = true;
  18552. }
  18553. }
  18554. }
  18555. lightIndex++;
  18556. if (lightIndex === maxSimultaneousLights)
  18557. break;
  18558. }
  18559. return needNormals;
  18560. };
  18561. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18562. var lightIndex = 0;
  18563. for (var index = 0; index < scene.lights.length; index++) {
  18564. var light = scene.lights[index];
  18565. if (!light.isEnabled()) {
  18566. continue;
  18567. }
  18568. if (!light.canAffectMesh(mesh)) {
  18569. continue;
  18570. }
  18571. if (light instanceof BABYLON.PointLight) {
  18572. // Point Light
  18573. light.transferToEffect(effect, "vLightData" + lightIndex);
  18574. }
  18575. else if (light instanceof BABYLON.DirectionalLight) {
  18576. // Directional Light
  18577. light.transferToEffect(effect, "vLightData" + lightIndex);
  18578. }
  18579. else if (light instanceof BABYLON.SpotLight) {
  18580. // Spot Light
  18581. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18582. }
  18583. else if (light instanceof BABYLON.HemisphericLight) {
  18584. // Hemispheric Light
  18585. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18586. }
  18587. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18588. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18589. if (defines["SPECULARTERM"]) {
  18590. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18591. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18592. }
  18593. // Shadows
  18594. if (scene.shadowsEnabled) {
  18595. var shadowGenerator = light.getShadowGenerator();
  18596. if (mesh.receiveShadows && shadowGenerator) {
  18597. if (!light.needCube()) {
  18598. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18599. }
  18600. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18601. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18602. }
  18603. }
  18604. lightIndex++;
  18605. if (lightIndex === maxSimultaneousLights)
  18606. break;
  18607. }
  18608. };
  18609. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18610. if (this.checkReadyOnlyOnce) {
  18611. if (this._wasPreviouslyReady) {
  18612. return true;
  18613. }
  18614. }
  18615. var scene = this.getScene();
  18616. if (!this.checkReadyOnEveryCall) {
  18617. if (this._renderId === scene.getRenderId()) {
  18618. if (this._checkCache(scene, mesh, useInstances)) {
  18619. return true;
  18620. }
  18621. }
  18622. }
  18623. var engine = scene.getEngine();
  18624. var needNormals = false;
  18625. var needUVs = false;
  18626. this._defines.reset();
  18627. // Textures
  18628. if (scene.texturesEnabled) {
  18629. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18630. if (!this.diffuseTexture.isReady()) {
  18631. return false;
  18632. }
  18633. else {
  18634. needUVs = true;
  18635. this._defines.DIFFUSE = true;
  18636. }
  18637. }
  18638. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18639. if (!this.ambientTexture.isReady()) {
  18640. return false;
  18641. }
  18642. else {
  18643. needUVs = true;
  18644. this._defines.AMBIENT = true;
  18645. }
  18646. }
  18647. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18648. if (!this.opacityTexture.isReady()) {
  18649. return false;
  18650. }
  18651. else {
  18652. needUVs = true;
  18653. this._defines.OPACITY = true;
  18654. if (this.opacityTexture.getAlphaFromRGB) {
  18655. this._defines.OPACITYRGB = true;
  18656. }
  18657. }
  18658. }
  18659. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18660. if (!this.reflectionTexture.isReady()) {
  18661. return false;
  18662. }
  18663. else {
  18664. needNormals = true;
  18665. this._defines.REFLECTION = true;
  18666. if (this.roughness > 0) {
  18667. this._defines.ROUGHNESS = true;
  18668. }
  18669. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18670. this._defines.INVERTCUBICMAP = true;
  18671. }
  18672. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18673. switch (this.reflectionTexture.coordinatesMode) {
  18674. case BABYLON.Texture.CUBIC_MODE:
  18675. case BABYLON.Texture.INVCUBIC_MODE:
  18676. this._defines.REFLECTIONMAP_CUBIC = true;
  18677. break;
  18678. case BABYLON.Texture.EXPLICIT_MODE:
  18679. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18680. break;
  18681. case BABYLON.Texture.PLANAR_MODE:
  18682. this._defines.REFLECTIONMAP_PLANAR = true;
  18683. break;
  18684. case BABYLON.Texture.PROJECTION_MODE:
  18685. this._defines.REFLECTIONMAP_PROJECTION = true;
  18686. break;
  18687. case BABYLON.Texture.SKYBOX_MODE:
  18688. this._defines.REFLECTIONMAP_SKYBOX = true;
  18689. break;
  18690. case BABYLON.Texture.SPHERICAL_MODE:
  18691. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18692. break;
  18693. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18694. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18695. break;
  18696. }
  18697. }
  18698. }
  18699. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18700. if (!this.emissiveTexture.isReady()) {
  18701. return false;
  18702. }
  18703. else {
  18704. needUVs = true;
  18705. this._defines.EMISSIVE = true;
  18706. }
  18707. }
  18708. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18709. if (!this.lightmapTexture.isReady()) {
  18710. return false;
  18711. }
  18712. else {
  18713. needUVs = true;
  18714. this._defines.LIGHTMAP = true;
  18715. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18716. }
  18717. }
  18718. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18719. if (!this.specularTexture.isReady()) {
  18720. return false;
  18721. }
  18722. else {
  18723. needUVs = true;
  18724. this._defines.SPECULAR = true;
  18725. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18726. }
  18727. }
  18728. }
  18729. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18730. if (!this.bumpTexture.isReady()) {
  18731. return false;
  18732. }
  18733. else {
  18734. needUVs = true;
  18735. this._defines.BUMP = true;
  18736. }
  18737. }
  18738. // Effect
  18739. if (scene.clipPlane) {
  18740. this._defines.CLIPPLANE = true;
  18741. }
  18742. if (engine.getAlphaTesting()) {
  18743. this._defines.ALPHATEST = true;
  18744. }
  18745. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18746. this._defines.ALPHAFROMDIFFUSE = true;
  18747. }
  18748. if (this.useEmissiveAsIllumination) {
  18749. this._defines.EMISSIVEASILLUMINATION = true;
  18750. }
  18751. if (this.linkEmissiveWithDiffuse) {
  18752. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18753. }
  18754. if (this.useReflectionFresnelFromSpecular) {
  18755. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18756. }
  18757. // Point size
  18758. if (this.pointsCloud || scene.forcePointsCloud) {
  18759. this._defines.POINTSIZE = true;
  18760. }
  18761. // Fog
  18762. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18763. this._defines.FOG = true;
  18764. }
  18765. if (scene.lightsEnabled && !this.disableLighting) {
  18766. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18767. }
  18768. if (StandardMaterial.FresnelEnabled) {
  18769. // Fresnel
  18770. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18771. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18772. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18773. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18774. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18775. this._defines.DIFFUSEFRESNEL = true;
  18776. }
  18777. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18778. this._defines.OPACITYFRESNEL = true;
  18779. }
  18780. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18781. this._defines.REFLECTIONFRESNEL = true;
  18782. }
  18783. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18784. this._defines.EMISSIVEFRESNEL = true;
  18785. }
  18786. needNormals = true;
  18787. this._defines.FRESNEL = true;
  18788. }
  18789. }
  18790. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18791. this._defines.SPECULAROVERALPHA = true;
  18792. }
  18793. // Attribs
  18794. if (mesh) {
  18795. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18796. this._defines.NORMAL = true;
  18797. }
  18798. if (needUVs) {
  18799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18800. this._defines.UV1 = true;
  18801. }
  18802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18803. this._defines.UV2 = true;
  18804. }
  18805. }
  18806. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18807. this._defines.VERTEXCOLOR = true;
  18808. if (mesh.hasVertexAlpha) {
  18809. this._defines.VERTEXALPHA = true;
  18810. }
  18811. }
  18812. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18813. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  18814. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18815. }
  18816. // Instances
  18817. if (useInstances) {
  18818. this._defines.INSTANCES = true;
  18819. }
  18820. }
  18821. // Get correct effect
  18822. if (!this._defines.isEqual(this._cachedDefines)) {
  18823. this._defines.cloneTo(this._cachedDefines);
  18824. scene.resetCachedMaterial();
  18825. // Fallbacks
  18826. var fallbacks = new BABYLON.EffectFallbacks();
  18827. if (this._defines.REFLECTION) {
  18828. fallbacks.addFallback(0, "REFLECTION");
  18829. }
  18830. if (this._defines.SPECULAR) {
  18831. fallbacks.addFallback(0, "SPECULAR");
  18832. }
  18833. if (this._defines.BUMP) {
  18834. fallbacks.addFallback(0, "BUMP");
  18835. }
  18836. if (this._defines.SPECULAROVERALPHA) {
  18837. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18838. }
  18839. if (this._defines.FOG) {
  18840. fallbacks.addFallback(1, "FOG");
  18841. }
  18842. if (this._defines.POINTSIZE) {
  18843. fallbacks.addFallback(0, "POINTSIZE");
  18844. }
  18845. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18846. if (!this._defines["LIGHT" + lightIndex]) {
  18847. continue;
  18848. }
  18849. if (lightIndex > 0) {
  18850. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18851. }
  18852. if (this._defines["SHADOW" + lightIndex]) {
  18853. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18854. }
  18855. if (this._defines["SHADOWPCF" + lightIndex]) {
  18856. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18857. }
  18858. if (this._defines["SHADOWVSM" + lightIndex]) {
  18859. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18860. }
  18861. }
  18862. if (this._defines.SPECULARTERM) {
  18863. fallbacks.addFallback(0, "SPECULARTERM");
  18864. }
  18865. if (this._defines.DIFFUSEFRESNEL) {
  18866. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18867. }
  18868. if (this._defines.OPACITYFRESNEL) {
  18869. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18870. }
  18871. if (this._defines.REFLECTIONFRESNEL) {
  18872. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18873. }
  18874. if (this._defines.EMISSIVEFRESNEL) {
  18875. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18876. }
  18877. if (this._defines.FRESNEL) {
  18878. fallbacks.addFallback(4, "FRESNEL");
  18879. }
  18880. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18881. fallbacks.addCPUSkinningFallback(0, mesh);
  18882. }
  18883. //Attributes
  18884. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18885. if (this._defines.NORMAL) {
  18886. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18887. }
  18888. if (this._defines.UV1) {
  18889. attribs.push(BABYLON.VertexBuffer.UVKind);
  18890. }
  18891. if (this._defines.UV2) {
  18892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18893. }
  18894. if (this._defines.VERTEXCOLOR) {
  18895. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18896. }
  18897. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18900. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  18901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  18902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  18903. }
  18904. }
  18905. if (this._defines.INSTANCES) {
  18906. attribs.push("world0");
  18907. attribs.push("world1");
  18908. attribs.push("world2");
  18909. attribs.push("world3");
  18910. }
  18911. // Legacy browser patch
  18912. var shaderName = "default";
  18913. if (!scene.getEngine().getCaps().standardDerivatives) {
  18914. shaderName = "legacydefault";
  18915. }
  18916. var join = this._defines.toString();
  18917. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18918. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18919. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18920. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18921. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18922. "vFogInfos", "vFogColor", "pointSize",
  18923. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18924. "mBones",
  18925. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18926. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18927. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18928. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18929. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18930. ], join, fallbacks, this.onCompiled, this.onError);
  18931. }
  18932. if (!this._effect.isReady()) {
  18933. return false;
  18934. }
  18935. this._renderId = scene.getRenderId();
  18936. this._wasPreviouslyReady = true;
  18937. if (mesh) {
  18938. if (!mesh._materialDefines) {
  18939. mesh._materialDefines = new StandardMaterialDefines();
  18940. }
  18941. this._defines.cloneTo(mesh._materialDefines);
  18942. }
  18943. return true;
  18944. };
  18945. StandardMaterial.prototype.unbind = function () {
  18946. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18947. this._effect.setTexture("reflection2DSampler", null);
  18948. }
  18949. _super.prototype.unbind.call(this);
  18950. };
  18951. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18952. this._effect.setMatrix("world", world);
  18953. };
  18954. StandardMaterial.prototype.bind = function (world, mesh) {
  18955. var scene = this.getScene();
  18956. // Matrices
  18957. this.bindOnlyWorldMatrix(world);
  18958. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18959. // Bones
  18960. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18961. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18962. }
  18963. if (scene.getCachedMaterial() !== this) {
  18964. if (StandardMaterial.FresnelEnabled) {
  18965. // Fresnel
  18966. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18967. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18968. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18969. }
  18970. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18971. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18972. }
  18973. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18974. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18975. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18976. }
  18977. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18978. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18979. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18980. }
  18981. }
  18982. // Textures
  18983. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18984. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18985. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18986. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18987. }
  18988. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18989. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18990. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18991. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18992. }
  18993. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18994. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18995. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18996. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18997. }
  18998. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18999. if (this.reflectionTexture.isCube) {
  19000. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19001. }
  19002. else {
  19003. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19004. }
  19005. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19006. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19007. }
  19008. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19009. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19010. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19011. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19012. }
  19013. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19014. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19015. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19016. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19017. }
  19018. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19019. this._effect.setTexture("specularSampler", this.specularTexture);
  19020. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19021. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19022. }
  19023. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19024. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19025. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19026. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19027. }
  19028. // Clip plane
  19029. if (scene.clipPlane) {
  19030. var clipPlane = scene.clipPlane;
  19031. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19032. }
  19033. // Point size
  19034. if (this.pointsCloud) {
  19035. this._effect.setFloat("pointSize", this.pointSize);
  19036. }
  19037. // Colors
  19038. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19039. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19040. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19041. if (this._defines.SPECULARTERM) {
  19042. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19043. }
  19044. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19045. }
  19046. // Diffuse
  19047. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19048. // Lights
  19049. if (scene.lightsEnabled && !this.disableLighting) {
  19050. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19051. }
  19052. // View
  19053. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19054. this._effect.setMatrix("view", scene.getViewMatrix());
  19055. }
  19056. // Fog
  19057. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19058. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19059. this._effect.setColor3("vFogColor", scene.fogColor);
  19060. }
  19061. _super.prototype.bind.call(this, world, mesh);
  19062. };
  19063. StandardMaterial.prototype.getAnimatables = function () {
  19064. var results = [];
  19065. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19066. results.push(this.diffuseTexture);
  19067. }
  19068. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19069. results.push(this.ambientTexture);
  19070. }
  19071. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19072. results.push(this.opacityTexture);
  19073. }
  19074. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19075. results.push(this.reflectionTexture);
  19076. }
  19077. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19078. results.push(this.emissiveTexture);
  19079. }
  19080. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19081. results.push(this.specularTexture);
  19082. }
  19083. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19084. results.push(this.bumpTexture);
  19085. }
  19086. return results;
  19087. };
  19088. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19089. if (this.diffuseTexture) {
  19090. this.diffuseTexture.dispose();
  19091. }
  19092. if (this.ambientTexture) {
  19093. this.ambientTexture.dispose();
  19094. }
  19095. if (this.opacityTexture) {
  19096. this.opacityTexture.dispose();
  19097. }
  19098. if (this.reflectionTexture) {
  19099. this.reflectionTexture.dispose();
  19100. }
  19101. if (this.emissiveTexture) {
  19102. this.emissiveTexture.dispose();
  19103. }
  19104. if (this.specularTexture) {
  19105. this.specularTexture.dispose();
  19106. }
  19107. if (this.bumpTexture) {
  19108. this.bumpTexture.dispose();
  19109. }
  19110. _super.prototype.dispose.call(this, forceDisposeEffect);
  19111. };
  19112. StandardMaterial.prototype.clone = function (name) {
  19113. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19114. // Base material
  19115. this.copyTo(newStandardMaterial);
  19116. // Standard material
  19117. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19118. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19119. }
  19120. if (this.ambientTexture && this.ambientTexture.clone) {
  19121. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19122. }
  19123. if (this.opacityTexture && this.opacityTexture.clone) {
  19124. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19125. }
  19126. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19127. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19128. }
  19129. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19130. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19131. }
  19132. if (this.specularTexture && this.specularTexture.clone) {
  19133. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19134. }
  19135. if (this.bumpTexture && this.bumpTexture.clone) {
  19136. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19137. }
  19138. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19139. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19140. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19141. }
  19142. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19143. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19144. newStandardMaterial.specularColor = this.specularColor.clone();
  19145. newStandardMaterial.specularPower = this.specularPower;
  19146. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19147. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19148. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19149. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19150. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19151. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19152. newStandardMaterial.roughness = this.roughness;
  19153. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19154. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19155. }
  19156. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19157. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19158. }
  19159. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19160. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19161. }
  19162. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19163. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19164. }
  19165. return newStandardMaterial;
  19166. };
  19167. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19168. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19169. // Statics
  19170. // Flags used to enable or disable a type of texture for all Standard Materials
  19171. StandardMaterial.DiffuseTextureEnabled = true;
  19172. StandardMaterial.AmbientTextureEnabled = true;
  19173. StandardMaterial.OpacityTextureEnabled = true;
  19174. StandardMaterial.ReflectionTextureEnabled = true;
  19175. StandardMaterial.EmissiveTextureEnabled = true;
  19176. StandardMaterial.SpecularTextureEnabled = true;
  19177. StandardMaterial.BumpTextureEnabled = true;
  19178. StandardMaterial.FresnelEnabled = true;
  19179. StandardMaterial.LightmapEnabled = true;
  19180. return StandardMaterial;
  19181. })(BABYLON.Material);
  19182. BABYLON.StandardMaterial = StandardMaterial;
  19183. })(BABYLON || (BABYLON = {}));
  19184. var BABYLON;
  19185. (function (BABYLON) {
  19186. var MultiMaterial = (function (_super) {
  19187. __extends(MultiMaterial, _super);
  19188. function MultiMaterial(name, scene) {
  19189. _super.call(this, name, scene, true);
  19190. this.subMaterials = new Array();
  19191. scene.multiMaterials.push(this);
  19192. }
  19193. // Properties
  19194. MultiMaterial.prototype.getSubMaterial = function (index) {
  19195. if (index < 0 || index >= this.subMaterials.length) {
  19196. return this.getScene().defaultMaterial;
  19197. }
  19198. return this.subMaterials[index];
  19199. };
  19200. // Methods
  19201. MultiMaterial.prototype.isReady = function (mesh) {
  19202. for (var index = 0; index < this.subMaterials.length; index++) {
  19203. var subMaterial = this.subMaterials[index];
  19204. if (subMaterial) {
  19205. if (!this.subMaterials[index].isReady(mesh)) {
  19206. return false;
  19207. }
  19208. }
  19209. }
  19210. return true;
  19211. };
  19212. MultiMaterial.prototype.clone = function (name) {
  19213. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19214. for (var index = 0; index < this.subMaterials.length; index++) {
  19215. var subMaterial = this.subMaterials[index];
  19216. newMultiMaterial.subMaterials.push(subMaterial);
  19217. }
  19218. return newMultiMaterial;
  19219. };
  19220. return MultiMaterial;
  19221. })(BABYLON.Material);
  19222. BABYLON.MultiMaterial = MultiMaterial;
  19223. })(BABYLON || (BABYLON = {}));
  19224. var BABYLON;
  19225. (function (BABYLON) {
  19226. var SceneLoader = (function () {
  19227. function SceneLoader() {
  19228. }
  19229. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19230. get: function () {
  19231. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19232. },
  19233. set: function (value) {
  19234. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19240. get: function () {
  19241. return SceneLoader._ShowLoadingScreen;
  19242. },
  19243. set: function (value) {
  19244. SceneLoader._ShowLoadingScreen = value;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19250. var dotPosition = sceneFilename.lastIndexOf(".");
  19251. var queryStringPosition = sceneFilename.indexOf("?");
  19252. if (queryStringPosition === -1) {
  19253. queryStringPosition = sceneFilename.length;
  19254. }
  19255. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19256. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19257. var plugin = this._registeredPlugins[index];
  19258. if (plugin.extensions.indexOf(extension) !== -1) {
  19259. return plugin;
  19260. }
  19261. }
  19262. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19263. };
  19264. // Public functions
  19265. SceneLoader.RegisterPlugin = function (plugin) {
  19266. plugin.extensions = plugin.extensions.toLowerCase();
  19267. SceneLoader._registeredPlugins.push(plugin);
  19268. };
  19269. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19270. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19271. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19272. return;
  19273. }
  19274. var loadingToken = {};
  19275. scene._addPendingData(loadingToken);
  19276. var manifestChecked = function (success) {
  19277. scene.database = database;
  19278. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19279. var importMeshFromData = function (data) {
  19280. var meshes = [];
  19281. var particleSystems = [];
  19282. var skeletons = [];
  19283. try {
  19284. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19285. if (onerror) {
  19286. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19287. }
  19288. scene._removePendingData(loadingToken);
  19289. return;
  19290. }
  19291. }
  19292. catch (e) {
  19293. if (onerror) {
  19294. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19295. }
  19296. scene._removePendingData(loadingToken);
  19297. return;
  19298. }
  19299. if (onsuccess) {
  19300. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19301. onsuccess(meshes, particleSystems, skeletons);
  19302. scene._removePendingData(loadingToken);
  19303. }
  19304. };
  19305. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19306. // Direct load
  19307. importMeshFromData(sceneFilename.substr(5));
  19308. return;
  19309. }
  19310. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19311. importMeshFromData(data);
  19312. }, progressCallBack, database);
  19313. };
  19314. if (scene.getEngine().enableOfflineSupport) {
  19315. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19316. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19317. }
  19318. else {
  19319. manifestChecked(true);
  19320. }
  19321. };
  19322. /**
  19323. * Load a scene
  19324. * @param rootUrl a string that defines the root url for scene and resources
  19325. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19326. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19327. */
  19328. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19329. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19330. };
  19331. /**
  19332. * Append a scene
  19333. * @param rootUrl a string that defines the root url for scene and resources
  19334. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19335. * @param scene is the instance of BABYLON.Scene to append to
  19336. */
  19337. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19338. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19339. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19340. return;
  19341. }
  19342. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19343. var database;
  19344. var loadingToken = {};
  19345. scene._addPendingData(loadingToken);
  19346. if (SceneLoader.ShowLoadingScreen) {
  19347. scene.getEngine().displayLoadingUI();
  19348. }
  19349. var loadSceneFromData = function (data) {
  19350. scene.database = database;
  19351. if (!plugin.load(scene, data, rootUrl)) {
  19352. if (onerror) {
  19353. onerror(scene);
  19354. }
  19355. scene._removePendingData(loadingToken);
  19356. scene.getEngine().hideLoadingUI();
  19357. return;
  19358. }
  19359. if (onsuccess) {
  19360. onsuccess(scene);
  19361. }
  19362. scene._removePendingData(loadingToken);
  19363. if (SceneLoader.ShowLoadingScreen) {
  19364. scene.executeWhenReady(function () {
  19365. scene.getEngine().hideLoadingUI();
  19366. });
  19367. }
  19368. };
  19369. var manifestChecked = function (success) {
  19370. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19371. };
  19372. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19373. // Direct load
  19374. loadSceneFromData(sceneFilename.substr(5));
  19375. return;
  19376. }
  19377. if (rootUrl.indexOf("file:") === -1) {
  19378. if (scene.getEngine().enableOfflineSupport) {
  19379. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19380. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19381. }
  19382. else {
  19383. manifestChecked(true);
  19384. }
  19385. }
  19386. else {
  19387. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19388. }
  19389. };
  19390. // Flags
  19391. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19392. SceneLoader._ShowLoadingScreen = true;
  19393. // Members
  19394. SceneLoader._registeredPlugins = new Array();
  19395. return SceneLoader;
  19396. })();
  19397. BABYLON.SceneLoader = SceneLoader;
  19398. ;
  19399. })(BABYLON || (BABYLON = {}));
  19400. var BABYLON;
  19401. (function (BABYLON) {
  19402. var Internals;
  19403. (function (Internals) {
  19404. var checkColors4 = function (colors, count) {
  19405. // Check if color3 was used
  19406. if (colors.length === count * 3) {
  19407. var colors4 = [];
  19408. for (var index = 0; index < colors.length; index += 3) {
  19409. var newIndex = (index / 3) * 4;
  19410. colors4[newIndex] = colors[index];
  19411. colors4[newIndex + 1] = colors[index + 1];
  19412. colors4[newIndex + 2] = colors[index + 2];
  19413. colors4[newIndex + 3] = 1.0;
  19414. }
  19415. return colors4;
  19416. }
  19417. return colors;
  19418. };
  19419. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19420. var texture = null;
  19421. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19422. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19423. texture.name = parsedTexture.name;
  19424. texture.hasAlpha = parsedTexture.hasAlpha;
  19425. texture.level = parsedTexture.level;
  19426. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19427. }
  19428. return texture;
  19429. };
  19430. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19431. if (parsedTexture.isCube) {
  19432. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19433. }
  19434. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19435. return null;
  19436. }
  19437. var texture;
  19438. if (parsedTexture.mirrorPlane) {
  19439. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19440. texture._waitingRenderList = parsedTexture.renderList;
  19441. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19442. }
  19443. else if (parsedTexture.isRenderTarget) {
  19444. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19445. texture._waitingRenderList = parsedTexture.renderList;
  19446. }
  19447. else {
  19448. if (parsedTexture.base64String) {
  19449. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19450. }
  19451. else {
  19452. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19453. }
  19454. }
  19455. texture.name = parsedTexture.name;
  19456. texture.hasAlpha = parsedTexture.hasAlpha;
  19457. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19458. texture.level = parsedTexture.level;
  19459. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19460. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19461. texture.uOffset = parsedTexture.uOffset;
  19462. texture.vOffset = parsedTexture.vOffset;
  19463. texture.uScale = parsedTexture.uScale;
  19464. texture.vScale = parsedTexture.vScale;
  19465. texture.uAng = parsedTexture.uAng;
  19466. texture.vAng = parsedTexture.vAng;
  19467. texture.wAng = parsedTexture.wAng;
  19468. texture.wrapU = parsedTexture.wrapU;
  19469. texture.wrapV = parsedTexture.wrapV;
  19470. // Animations
  19471. if (parsedTexture.animations) {
  19472. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19473. var parsedAnimation = parsedTexture.animations[animationIndex];
  19474. texture.animations.push(parseAnimation(parsedAnimation));
  19475. }
  19476. }
  19477. return texture;
  19478. };
  19479. var parseSkeleton = function (parsedSkeleton, scene) {
  19480. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19481. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19482. var parsedBone = parsedSkeleton.bones[index];
  19483. var parentBone = null;
  19484. if (parsedBone.parentBoneIndex > -1) {
  19485. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19486. }
  19487. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19488. if (parsedBone.animation) {
  19489. bone.animations.push(parseAnimation(parsedBone.animation));
  19490. }
  19491. }
  19492. return skeleton;
  19493. };
  19494. var parseFresnelParameters = function (parsedFresnelParameters) {
  19495. var fresnelParameters = new BABYLON.FresnelParameters();
  19496. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19497. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19498. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19499. fresnelParameters.bias = parsedFresnelParameters.bias;
  19500. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19501. return fresnelParameters;
  19502. };
  19503. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19504. var material;
  19505. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19506. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19507. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19508. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19509. material.specularPower = parsedMaterial.specularPower;
  19510. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19511. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19512. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19513. material.alpha = parsedMaterial.alpha;
  19514. material.id = parsedMaterial.id;
  19515. if (parsedMaterial.disableDepthWrite) {
  19516. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19517. }
  19518. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19519. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19520. material.wireframe = parsedMaterial.wireframe;
  19521. if (parsedMaterial.diffuseTexture) {
  19522. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19523. }
  19524. if (parsedMaterial.diffuseFresnelParameters) {
  19525. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19526. }
  19527. if (parsedMaterial.ambientTexture) {
  19528. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19529. }
  19530. if (parsedMaterial.opacityTexture) {
  19531. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19532. }
  19533. if (parsedMaterial.opacityFresnelParameters) {
  19534. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19535. }
  19536. if (parsedMaterial.reflectionTexture) {
  19537. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19538. }
  19539. if (parsedMaterial.reflectionFresnelParameters) {
  19540. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19541. }
  19542. if (parsedMaterial.emissiveTexture) {
  19543. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19544. }
  19545. if (parsedMaterial.lightmapTexture) {
  19546. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19547. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19548. }
  19549. if (parsedMaterial.emissiveFresnelParameters) {
  19550. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19551. }
  19552. if (parsedMaterial.specularTexture) {
  19553. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19554. }
  19555. if (parsedMaterial.bumpTexture) {
  19556. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19557. }
  19558. if (parsedMaterial.checkReadyOnlyOnce) {
  19559. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19560. }
  19561. return material;
  19562. };
  19563. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19564. for (var index = 0; index < parsedData.materials.length; index++) {
  19565. var parsedMaterial = parsedData.materials[index];
  19566. if (parsedMaterial.id === id) {
  19567. return parseMaterial(parsedMaterial, scene, rootUrl);
  19568. }
  19569. }
  19570. return null;
  19571. };
  19572. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19573. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19574. multiMaterial.id = parsedMultiMaterial.id;
  19575. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19576. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19577. var subMatId = parsedMultiMaterial.materials[matIndex];
  19578. if (subMatId) {
  19579. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19580. }
  19581. else {
  19582. multiMaterial.subMaterials.push(null);
  19583. }
  19584. }
  19585. return multiMaterial;
  19586. };
  19587. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19588. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19589. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19590. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19591. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19592. var parsedFlare = parsedLensFlareSystem.flares[index];
  19593. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19594. }
  19595. return lensFlareSystem;
  19596. };
  19597. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19598. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19599. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19600. if (parsedParticleSystem.textureName) {
  19601. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19602. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19603. }
  19604. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19605. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19606. particleSystem.minSize = parsedParticleSystem.minSize;
  19607. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19608. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19609. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19610. particleSystem.emitter = emitter;
  19611. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19612. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19613. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19614. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19615. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19616. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19617. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19618. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19619. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19620. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19621. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19622. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19623. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19624. particleSystem.start();
  19625. return particleSystem;
  19626. };
  19627. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19628. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19629. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19630. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19631. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19632. shadowGenerator.getShadowMap().renderList.push(mesh);
  19633. }
  19634. if (parsedShadowGenerator.usePoissonSampling) {
  19635. shadowGenerator.usePoissonSampling = true;
  19636. }
  19637. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19638. shadowGenerator.useVarianceShadowMap = true;
  19639. }
  19640. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19641. shadowGenerator.useBlurVarianceShadowMap = true;
  19642. if (parsedShadowGenerator.blurScale) {
  19643. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19644. }
  19645. if (parsedShadowGenerator.blurBoxOffset) {
  19646. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19647. }
  19648. }
  19649. if (parsedShadowGenerator.bias !== undefined) {
  19650. shadowGenerator.bias = parsedShadowGenerator.bias;
  19651. }
  19652. return shadowGenerator;
  19653. };
  19654. var parseAnimation = function (parsedAnimation) {
  19655. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19656. var dataType = parsedAnimation.dataType;
  19657. var keys = [];
  19658. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19659. var key = parsedAnimation.keys[index];
  19660. var data;
  19661. switch (dataType) {
  19662. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19663. data = key.values[0];
  19664. break;
  19665. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19666. data = BABYLON.Quaternion.FromArray(key.values);
  19667. break;
  19668. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19669. data = BABYLON.Matrix.FromArray(key.values);
  19670. break;
  19671. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19672. default:
  19673. data = BABYLON.Vector3.FromArray(key.values);
  19674. break;
  19675. }
  19676. keys.push({
  19677. frame: key.frame,
  19678. value: data
  19679. });
  19680. }
  19681. animation.setKeys(keys);
  19682. return animation;
  19683. };
  19684. var parseLight = function (parsedLight, scene) {
  19685. var light;
  19686. switch (parsedLight.type) {
  19687. case 0:
  19688. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19689. break;
  19690. case 1:
  19691. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19692. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19693. break;
  19694. case 2:
  19695. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19696. break;
  19697. case 3:
  19698. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19699. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19700. break;
  19701. }
  19702. light.id = parsedLight.id;
  19703. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19704. if (parsedLight.intensity !== undefined) {
  19705. light.intensity = parsedLight.intensity;
  19706. }
  19707. if (parsedLight.range) {
  19708. light.range = parsedLight.range;
  19709. }
  19710. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19711. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19712. if (parsedLight.excludedMeshesIds) {
  19713. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19714. }
  19715. // Parent
  19716. if (parsedLight.parentId) {
  19717. light._waitingParentId = parsedLight.parentId;
  19718. }
  19719. if (parsedLight.includedOnlyMeshesIds) {
  19720. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19721. }
  19722. // Animations
  19723. if (parsedLight.animations) {
  19724. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19725. var parsedAnimation = parsedLight.animations[animationIndex];
  19726. light.animations.push(parseAnimation(parsedAnimation));
  19727. }
  19728. }
  19729. if (parsedLight.autoAnimate) {
  19730. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19731. }
  19732. };
  19733. var parseCamera = function (parsedCamera, scene) {
  19734. var camera;
  19735. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19736. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19737. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19738. var alpha = parsedCamera.alpha;
  19739. var beta = parsedCamera.beta;
  19740. var radius = parsedCamera.radius;
  19741. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19742. var interaxial_distance = parsedCamera.interaxial_distance;
  19743. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19744. }
  19745. else {
  19746. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19747. }
  19748. }
  19749. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19750. interaxial_distance = parsedCamera.interaxial_distance;
  19751. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19752. }
  19753. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19754. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19755. }
  19756. else if (parsedCamera.type === "FollowCamera") {
  19757. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19758. camera.heightOffset = parsedCamera.heightOffset;
  19759. camera.radius = parsedCamera.radius;
  19760. camera.rotationOffset = parsedCamera.rotationOffset;
  19761. if (lockedTargetMesh)
  19762. camera.target = lockedTargetMesh;
  19763. }
  19764. else if (parsedCamera.type === "GamepadCamera") {
  19765. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19766. }
  19767. else if (parsedCamera.type === "TouchCamera") {
  19768. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19769. }
  19770. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19771. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19772. }
  19773. else if (parsedCamera.type === "WebVRFreeCamera") {
  19774. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19775. }
  19776. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19777. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19778. }
  19779. else {
  19780. // Free Camera is the default value
  19781. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19782. }
  19783. // apply 3d rig, when found
  19784. if (parsedCamera.cameraRigMode) {
  19785. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19786. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19787. }
  19788. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19789. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19790. camera.lockedTarget = lockedTargetMesh;
  19791. }
  19792. camera.id = parsedCamera.id;
  19793. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19794. // Parent
  19795. if (parsedCamera.parentId) {
  19796. camera._waitingParentId = parsedCamera.parentId;
  19797. }
  19798. // Target
  19799. if (parsedCamera.target) {
  19800. if (camera.setTarget) {
  19801. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19802. }
  19803. else {
  19804. //For ArcRotate
  19805. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19806. }
  19807. }
  19808. else {
  19809. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19810. }
  19811. camera.fov = parsedCamera.fov;
  19812. camera.minZ = parsedCamera.minZ;
  19813. camera.maxZ = parsedCamera.maxZ;
  19814. camera.speed = parsedCamera.speed;
  19815. camera.inertia = parsedCamera.inertia;
  19816. camera.checkCollisions = parsedCamera.checkCollisions;
  19817. camera.applyGravity = parsedCamera.applyGravity;
  19818. if (parsedCamera.ellipsoid) {
  19819. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19820. }
  19821. // Animations
  19822. if (parsedCamera.animations) {
  19823. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19824. var parsedAnimation = parsedCamera.animations[animationIndex];
  19825. camera.animations.push(parseAnimation(parsedAnimation));
  19826. }
  19827. }
  19828. if (parsedCamera.autoAnimate) {
  19829. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19830. }
  19831. // Layer Mask
  19832. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19833. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19834. }
  19835. else {
  19836. camera.layerMask = 0x0FFFFFFF;
  19837. }
  19838. return camera;
  19839. };
  19840. var parseGeometry = function (parsedGeometry, scene) {
  19841. var id = parsedGeometry.id;
  19842. return scene.getGeometryByID(id);
  19843. };
  19844. var parseBox = function (parsedBox, scene) {
  19845. if (parseGeometry(parsedBox, scene)) {
  19846. return null; // null since geometry could be something else than a box...
  19847. }
  19848. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19849. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19850. scene.pushGeometry(box, true);
  19851. return box;
  19852. };
  19853. var parseSphere = function (parsedSphere, scene) {
  19854. if (parseGeometry(parsedSphere, scene)) {
  19855. return null; // null since geometry could be something else than a sphere...
  19856. }
  19857. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19858. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19859. scene.pushGeometry(sphere, true);
  19860. return sphere;
  19861. };
  19862. var parseCylinder = function (parsedCylinder, scene) {
  19863. if (parseGeometry(parsedCylinder, scene)) {
  19864. return null; // null since geometry could be something else than a cylinder...
  19865. }
  19866. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19867. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19868. scene.pushGeometry(cylinder, true);
  19869. return cylinder;
  19870. };
  19871. var parseTorus = function (parsedTorus, scene) {
  19872. if (parseGeometry(parsedTorus, scene)) {
  19873. return null; // null since geometry could be something else than a torus...
  19874. }
  19875. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19876. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19877. scene.pushGeometry(torus, true);
  19878. return torus;
  19879. };
  19880. var parseGround = function (parsedGround, scene) {
  19881. if (parseGeometry(parsedGround, scene)) {
  19882. return null; // null since geometry could be something else than a ground...
  19883. }
  19884. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19885. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19886. scene.pushGeometry(ground, true);
  19887. return ground;
  19888. };
  19889. var parsePlane = function (parsedPlane, scene) {
  19890. if (parseGeometry(parsedPlane, scene)) {
  19891. return null; // null since geometry could be something else than a plane...
  19892. }
  19893. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19894. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19895. scene.pushGeometry(plane, true);
  19896. return plane;
  19897. };
  19898. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19899. if (parseGeometry(parsedTorusKnot, scene)) {
  19900. return null; // null since geometry could be something else than a torusKnot...
  19901. }
  19902. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  19903. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19904. scene.pushGeometry(torusKnot, true);
  19905. return torusKnot;
  19906. };
  19907. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19908. if (parseGeometry(parsedVertexData, scene)) {
  19909. return null; // null since geometry could be a primitive
  19910. }
  19911. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19912. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19913. if (parsedVertexData.delayLoadingFile) {
  19914. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19915. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19916. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19917. geometry._delayInfo = [];
  19918. if (parsedVertexData.hasUVs) {
  19919. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19920. }
  19921. if (parsedVertexData.hasUVs2) {
  19922. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19923. }
  19924. if (parsedVertexData.hasUVs3) {
  19925. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19926. }
  19927. if (parsedVertexData.hasUVs4) {
  19928. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19929. }
  19930. if (parsedVertexData.hasUVs5) {
  19931. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19932. }
  19933. if (parsedVertexData.hasUVs6) {
  19934. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19935. }
  19936. if (parsedVertexData.hasColors) {
  19937. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19938. }
  19939. if (parsedVertexData.hasMatricesIndices) {
  19940. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19941. }
  19942. if (parsedVertexData.hasMatricesWeights) {
  19943. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19944. }
  19945. geometry._delayLoadingFunction = importVertexData;
  19946. }
  19947. else {
  19948. importVertexData(parsedVertexData, geometry);
  19949. }
  19950. scene.pushGeometry(geometry, true);
  19951. return geometry;
  19952. };
  19953. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19954. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19955. mesh.id = parsedMesh.id;
  19956. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19957. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19958. if (parsedMesh.rotationQuaternion) {
  19959. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19960. }
  19961. else if (parsedMesh.rotation) {
  19962. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19963. }
  19964. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19965. if (parsedMesh.localMatrix) {
  19966. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19967. }
  19968. else if (parsedMesh.pivotMatrix) {
  19969. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19970. }
  19971. mesh.setEnabled(parsedMesh.isEnabled);
  19972. mesh.isVisible = parsedMesh.isVisible;
  19973. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19974. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19975. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19976. if (parsedMesh.applyFog !== undefined) {
  19977. mesh.applyFog = parsedMesh.applyFog;
  19978. }
  19979. if (parsedMesh.pickable !== undefined) {
  19980. mesh.isPickable = parsedMesh.pickable;
  19981. }
  19982. if (parsedMesh.alphaIndex !== undefined) {
  19983. mesh.alphaIndex = parsedMesh.alphaIndex;
  19984. }
  19985. mesh.receiveShadows = parsedMesh.receiveShadows;
  19986. mesh.billboardMode = parsedMesh.billboardMode;
  19987. if (parsedMesh.visibility !== undefined) {
  19988. mesh.visibility = parsedMesh.visibility;
  19989. }
  19990. mesh.checkCollisions = parsedMesh.checkCollisions;
  19991. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19992. // freezeWorldMatrix
  19993. if (parsedMesh.freezeWorldMatrix) {
  19994. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19995. }
  19996. // Parent
  19997. if (parsedMesh.parentId) {
  19998. mesh._waitingParentId = parsedMesh.parentId;
  19999. }
  20000. // Actions
  20001. if (parsedMesh.actions !== undefined) {
  20002. mesh._waitingActions = parsedMesh.actions;
  20003. }
  20004. // Geometry
  20005. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20006. if (parsedMesh.delayLoadingFile) {
  20007. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20008. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20009. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20010. if (parsedMesh._binaryInfo) {
  20011. mesh._binaryInfo = parsedMesh._binaryInfo;
  20012. }
  20013. mesh._delayInfo = [];
  20014. if (parsedMesh.hasUVs) {
  20015. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20016. }
  20017. if (parsedMesh.hasUVs2) {
  20018. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20019. }
  20020. if (parsedMesh.hasUVs3) {
  20021. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20022. }
  20023. if (parsedMesh.hasUVs4) {
  20024. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20025. }
  20026. if (parsedMesh.hasUVs5) {
  20027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20028. }
  20029. if (parsedMesh.hasUVs6) {
  20030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20031. }
  20032. if (parsedMesh.hasColors) {
  20033. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20034. }
  20035. if (parsedMesh.hasMatricesIndices) {
  20036. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20037. }
  20038. if (parsedMesh.hasMatricesWeights) {
  20039. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20040. }
  20041. mesh._delayLoadingFunction = importGeometry;
  20042. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20043. mesh._checkDelayState();
  20044. }
  20045. }
  20046. else {
  20047. importGeometry(parsedMesh, mesh);
  20048. }
  20049. // Material
  20050. if (parsedMesh.materialId) {
  20051. mesh.setMaterialByID(parsedMesh.materialId);
  20052. }
  20053. else {
  20054. mesh.material = null;
  20055. }
  20056. // Skeleton
  20057. if (parsedMesh.skeletonId > -1) {
  20058. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20059. if (parsedMesh.numBoneInfluencers) {
  20060. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20061. }
  20062. }
  20063. // Physics
  20064. if (parsedMesh.physicsImpostor) {
  20065. if (!scene.isPhysicsEnabled()) {
  20066. scene.enablePhysics();
  20067. }
  20068. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20069. }
  20070. // Animations
  20071. if (parsedMesh.animations) {
  20072. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20073. var parsedAnimation = parsedMesh.animations[animationIndex];
  20074. mesh.animations.push(parseAnimation(parsedAnimation));
  20075. }
  20076. }
  20077. if (parsedMesh.autoAnimate) {
  20078. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20079. }
  20080. // Layer Mask
  20081. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20082. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20083. }
  20084. else {
  20085. mesh.layerMask = 0x0FFFFFFF;
  20086. }
  20087. // Instances
  20088. if (parsedMesh.instances) {
  20089. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20090. var parsedInstance = parsedMesh.instances[index];
  20091. var instance = mesh.createInstance(parsedInstance.name);
  20092. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20093. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20094. if (parsedInstance.rotationQuaternion) {
  20095. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20096. }
  20097. else if (parsedInstance.rotation) {
  20098. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20099. }
  20100. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20101. instance.checkCollisions = mesh.checkCollisions;
  20102. if (parsedMesh.animations) {
  20103. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20104. parsedAnimation = parsedMesh.animations[animationIndex];
  20105. instance.animations.push(parseAnimation(parsedAnimation));
  20106. }
  20107. }
  20108. }
  20109. }
  20110. return mesh;
  20111. };
  20112. var parseActions = function (parsedActions, object, scene) {
  20113. var actionManager = new BABYLON.ActionManager(scene);
  20114. if (object === null)
  20115. scene.actionManager = actionManager;
  20116. else
  20117. object.actionManager = actionManager;
  20118. // instanciate a new object
  20119. var instanciate = function (name, params) {
  20120. var newInstance = Object.create(BABYLON[name].prototype);
  20121. newInstance.constructor.apply(newInstance, params);
  20122. return newInstance;
  20123. };
  20124. var parseParameter = function (name, value, target, propertyPath) {
  20125. if (propertyPath === null) {
  20126. // String, boolean or float
  20127. var floatValue = parseFloat(value);
  20128. if (value === "true" || value === "false")
  20129. return value === "true";
  20130. else
  20131. return isNaN(floatValue) ? value : floatValue;
  20132. }
  20133. var effectiveTarget = propertyPath.split(".");
  20134. var values = value.split(",");
  20135. // Get effective Target
  20136. for (var i = 0; i < effectiveTarget.length; i++) {
  20137. target = target[effectiveTarget[i]];
  20138. }
  20139. // Return appropriate value with its type
  20140. if (typeof (target) === "boolean")
  20141. return values[0] === "true";
  20142. if (typeof (target) === "string")
  20143. return values[0];
  20144. // Parameters with multiple values such as Vector3 etc.
  20145. var split = new Array();
  20146. for (var i = 0; i < values.length; i++)
  20147. split.push(parseFloat(values[i]));
  20148. if (target instanceof BABYLON.Vector3)
  20149. return BABYLON.Vector3.FromArray(split);
  20150. if (target instanceof BABYLON.Vector4)
  20151. return BABYLON.Vector4.FromArray(split);
  20152. if (target instanceof BABYLON.Color3)
  20153. return BABYLON.Color3.FromArray(split);
  20154. if (target instanceof BABYLON.Color4)
  20155. return BABYLON.Color4.FromArray(split);
  20156. return parseFloat(values[0]);
  20157. };
  20158. // traverse graph per trigger
  20159. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20160. if (combineArray === void 0) { combineArray = null; }
  20161. if (parsedAction.detached)
  20162. return;
  20163. var parameters = new Array();
  20164. var target = null;
  20165. var propertyPath = null;
  20166. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20167. // Parameters
  20168. if (parsedAction.type === 2)
  20169. parameters.push(actionManager);
  20170. else
  20171. parameters.push(trigger);
  20172. if (combine) {
  20173. var actions = new Array();
  20174. for (var j = 0; j < parsedAction.combine.length; j++) {
  20175. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20176. }
  20177. parameters.push(actions);
  20178. }
  20179. else {
  20180. for (var i = 0; i < parsedAction.properties.length; i++) {
  20181. var value = parsedAction.properties[i].value;
  20182. var name = parsedAction.properties[i].name;
  20183. var targetType = parsedAction.properties[i].targetType;
  20184. if (name === "target")
  20185. if (targetType !== null && targetType === "SceneProperties")
  20186. value = target = scene;
  20187. else
  20188. value = target = scene.getNodeByName(value);
  20189. else if (name === "parent")
  20190. value = scene.getNodeByName(value);
  20191. else if (name === "sound")
  20192. value = scene.getSoundByName(value);
  20193. else if (name !== "propertyPath") {
  20194. if (parsedAction.type === 2 && name === "operator")
  20195. value = BABYLON.ValueCondition[value];
  20196. else
  20197. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20198. }
  20199. else {
  20200. propertyPath = value;
  20201. }
  20202. parameters.push(value);
  20203. }
  20204. }
  20205. if (combineArray === null) {
  20206. parameters.push(condition);
  20207. }
  20208. else {
  20209. parameters.push(null);
  20210. }
  20211. // If interpolate value action
  20212. if (parsedAction.name === "InterpolateValueAction") {
  20213. var param = parameters[parameters.length - 2];
  20214. parameters[parameters.length - 1] = param;
  20215. parameters[parameters.length - 2] = condition;
  20216. }
  20217. // Action or condition(s) and not CombineAction
  20218. var newAction = instanciate(parsedAction.name, parameters);
  20219. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20220. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20221. if (action)
  20222. action.then(nothing);
  20223. else
  20224. actionManager.registerAction(nothing);
  20225. action = nothing;
  20226. }
  20227. if (combineArray === null) {
  20228. if (newAction instanceof BABYLON.Condition) {
  20229. condition = newAction;
  20230. newAction = action;
  20231. }
  20232. else {
  20233. condition = null;
  20234. if (action)
  20235. action.then(newAction);
  20236. else
  20237. actionManager.registerAction(newAction);
  20238. }
  20239. }
  20240. else {
  20241. combineArray.push(newAction);
  20242. }
  20243. for (var i = 0; i < parsedAction.children.length; i++)
  20244. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20245. };
  20246. // triggers
  20247. for (var i = 0; i < parsedActions.children.length; i++) {
  20248. var triggerParams;
  20249. var trigger = parsedActions.children[i];
  20250. if (trigger.properties.length > 0) {
  20251. var param = trigger.properties[0].value;
  20252. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20253. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20254. }
  20255. else
  20256. triggerParams = BABYLON.ActionManager[trigger.name];
  20257. for (var j = 0; j < trigger.children.length; j++) {
  20258. if (!trigger.detached)
  20259. traverse(trigger.children[j], triggerParams, null, null);
  20260. }
  20261. }
  20262. };
  20263. var parseSound = function (parsedSound, scene, rootUrl) {
  20264. var soundName = parsedSound.name;
  20265. var soundUrl = rootUrl + soundName;
  20266. var options = {
  20267. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20268. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20269. rolloffFactor: parsedSound.rolloffFactor,
  20270. refDistance: parsedSound.refDistance,
  20271. distanceModel: parsedSound.distanceModel,
  20272. playbackRate: parsedSound.playbackRate
  20273. };
  20274. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20275. scene._addPendingData(newSound);
  20276. if (parsedSound.position) {
  20277. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20278. newSound.setPosition(soundPosition);
  20279. }
  20280. if (parsedSound.isDirectional) {
  20281. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20282. if (parsedSound.localDirectionToMesh) {
  20283. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20284. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20285. }
  20286. }
  20287. if (parsedSound.connectedMeshId) {
  20288. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20289. if (connectedMesh) {
  20290. newSound.attachToMesh(connectedMesh);
  20291. }
  20292. }
  20293. };
  20294. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20295. names = (names instanceof Array) ? names : [names];
  20296. for (var i in names) {
  20297. if (mesh.name === names[i]) {
  20298. hierarchyIds.push(mesh.id);
  20299. return true;
  20300. }
  20301. }
  20302. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20303. hierarchyIds.push(mesh.id);
  20304. return true;
  20305. }
  20306. return false;
  20307. };
  20308. var importVertexData = function (parsedVertexData, geometry) {
  20309. var vertexData = new BABYLON.VertexData();
  20310. // positions
  20311. var positions = parsedVertexData.positions;
  20312. if (positions) {
  20313. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20314. }
  20315. // normals
  20316. var normals = parsedVertexData.normals;
  20317. if (normals) {
  20318. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20319. }
  20320. // uvs
  20321. var uvs = parsedVertexData.uvs;
  20322. if (uvs) {
  20323. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20324. }
  20325. // uv2s
  20326. var uv2s = parsedVertexData.uv2s;
  20327. if (uv2s) {
  20328. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20329. }
  20330. // uv3s
  20331. var uv3s = parsedVertexData.uv3s;
  20332. if (uv3s) {
  20333. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20334. }
  20335. // uv4s
  20336. var uv4s = parsedVertexData.uv4s;
  20337. if (uv4s) {
  20338. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20339. }
  20340. // uv5s
  20341. var uv5s = parsedVertexData.uv5s;
  20342. if (uv5s) {
  20343. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20344. }
  20345. // uv6s
  20346. var uv6s = parsedVertexData.uv6s;
  20347. if (uv6s) {
  20348. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20349. }
  20350. // colors
  20351. var colors = parsedVertexData.colors;
  20352. if (colors) {
  20353. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20354. }
  20355. // matricesIndices
  20356. var matricesIndices = parsedVertexData.matricesIndices;
  20357. if (matricesIndices) {
  20358. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20359. }
  20360. // matricesWeights
  20361. var matricesWeights = parsedVertexData.matricesWeights;
  20362. if (matricesWeights) {
  20363. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20364. }
  20365. // indices
  20366. var indices = parsedVertexData.indices;
  20367. if (indices) {
  20368. vertexData.indices = indices;
  20369. }
  20370. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20371. };
  20372. var importGeometry = function (parsedGeometry, mesh) {
  20373. var scene = mesh.getScene();
  20374. // Geometry
  20375. var geometryId = parsedGeometry.geometryId;
  20376. if (geometryId) {
  20377. var geometry = scene.getGeometryByID(geometryId);
  20378. if (geometry) {
  20379. geometry.applyToMesh(mesh);
  20380. }
  20381. }
  20382. else if (parsedGeometry instanceof ArrayBuffer) {
  20383. var binaryInfo = mesh._binaryInfo;
  20384. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20385. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20386. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20387. }
  20388. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20389. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20390. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20391. }
  20392. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20393. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20394. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20395. }
  20396. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20397. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20398. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20399. }
  20400. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20401. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20402. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20403. }
  20404. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20405. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20406. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20407. }
  20408. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20409. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20410. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20411. }
  20412. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20413. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20414. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20415. }
  20416. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20417. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20418. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20419. }
  20420. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20421. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20423. }
  20424. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20425. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20427. }
  20428. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20429. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20430. mesh.setIndices(indicesData);
  20431. }
  20432. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20433. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20434. mesh.subMeshes = [];
  20435. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20436. var materialIndex = subMeshesData[(i * 5) + 0];
  20437. var verticesStart = subMeshesData[(i * 5) + 1];
  20438. var verticesCount = subMeshesData[(i * 5) + 2];
  20439. var indexStart = subMeshesData[(i * 5) + 3];
  20440. var indexCount = subMeshesData[(i * 5) + 4];
  20441. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20442. }
  20443. }
  20444. }
  20445. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20448. if (parsedGeometry.uvs) {
  20449. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20450. }
  20451. if (parsedGeometry.uvs2) {
  20452. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20453. }
  20454. if (parsedGeometry.uvs3) {
  20455. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20456. }
  20457. if (parsedGeometry.uvs4) {
  20458. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20459. }
  20460. if (parsedGeometry.uvs5) {
  20461. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20462. }
  20463. if (parsedGeometry.uvs6) {
  20464. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20465. }
  20466. if (parsedGeometry.colors) {
  20467. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20468. }
  20469. if (parsedGeometry.matricesIndices) {
  20470. if (!parsedGeometry.matricesIndices._isExpanded) {
  20471. var floatIndices = [];
  20472. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20473. var matricesIndex = parsedGeometry.matricesIndices[i];
  20474. floatIndices.push(matricesIndex & 0x000000FF);
  20475. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20476. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20477. floatIndices.push(matricesIndex >> 24);
  20478. }
  20479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20480. }
  20481. else {
  20482. delete parsedGeometry.matricesIndices._isExpanded;
  20483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20484. }
  20485. }
  20486. if (parsedGeometry.matricesIndicesExtra) {
  20487. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  20488. var floatIndices = [];
  20489. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  20490. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  20491. floatIndices.push(matricesIndex & 0x000000FF);
  20492. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20493. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20494. floatIndices.push(matricesIndex >> 24);
  20495. }
  20496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  20497. }
  20498. else {
  20499. delete parsedGeometry.matricesIndices._isExpanded;
  20500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  20501. }
  20502. }
  20503. if (parsedGeometry.matricesWeights) {
  20504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20505. }
  20506. if (parsedGeometry.matricesWeightsExtra) {
  20507. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  20508. }
  20509. mesh.setIndices(parsedGeometry.indices);
  20510. }
  20511. // SubMeshes
  20512. if (parsedGeometry.subMeshes) {
  20513. mesh.subMeshes = [];
  20514. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20515. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20516. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20517. }
  20518. }
  20519. // Flat shading
  20520. if (mesh._shouldGenerateFlatShading) {
  20521. mesh.convertToFlatShadedMesh();
  20522. delete mesh._shouldGenerateFlatShading;
  20523. }
  20524. // Update
  20525. mesh.computeWorldMatrix(true);
  20526. // Octree
  20527. if (scene._selectionOctree) {
  20528. scene._selectionOctree.addMesh(mesh);
  20529. }
  20530. };
  20531. BABYLON.SceneLoader.RegisterPlugin({
  20532. extensions: ".babylon",
  20533. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20534. var parsedData = JSON.parse(data);
  20535. var loadedSkeletonsIds = [];
  20536. var loadedMaterialsIds = [];
  20537. var hierarchyIds = [];
  20538. for (var index = 0; index < parsedData.meshes.length; index++) {
  20539. var parsedMesh = parsedData.meshes[index];
  20540. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20541. if (meshesNames instanceof Array) {
  20542. // Remove found mesh name from list.
  20543. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20544. }
  20545. //Geometry?
  20546. if (parsedMesh.geometryId) {
  20547. //does the file contain geometries?
  20548. if (parsedData.geometries) {
  20549. //find the correct geometry and add it to the scene
  20550. var found = false;
  20551. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20552. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20553. return;
  20554. }
  20555. else {
  20556. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20557. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20558. switch (geometryType) {
  20559. case "boxes":
  20560. parseBox(parsedGeometryData, scene);
  20561. break;
  20562. case "spheres":
  20563. parseSphere(parsedGeometryData, scene);
  20564. break;
  20565. case "cylinders":
  20566. parseCylinder(parsedGeometryData, scene);
  20567. break;
  20568. case "toruses":
  20569. parseTorus(parsedGeometryData, scene);
  20570. break;
  20571. case "grounds":
  20572. parseGround(parsedGeometryData, scene);
  20573. break;
  20574. case "planes":
  20575. parsePlane(parsedGeometryData, scene);
  20576. break;
  20577. case "torusKnots":
  20578. parseTorusKnot(parsedGeometryData, scene);
  20579. break;
  20580. case "vertexData":
  20581. parseVertexData(parsedGeometryData, scene, rootUrl);
  20582. break;
  20583. }
  20584. found = true;
  20585. }
  20586. });
  20587. }
  20588. });
  20589. if (!found) {
  20590. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20591. }
  20592. }
  20593. }
  20594. // Material ?
  20595. if (parsedMesh.materialId) {
  20596. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20597. if (!materialFound && parsedData.multiMaterials) {
  20598. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20599. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20600. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20601. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20602. var subMatId = parsedMultiMaterial.materials[matIndex];
  20603. loadedMaterialsIds.push(subMatId);
  20604. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20605. }
  20606. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20607. parseMultiMaterial(parsedMultiMaterial, scene);
  20608. materialFound = true;
  20609. break;
  20610. }
  20611. }
  20612. }
  20613. if (!materialFound) {
  20614. loadedMaterialsIds.push(parsedMesh.materialId);
  20615. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20616. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20617. }
  20618. }
  20619. }
  20620. // Skeleton ?
  20621. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20622. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20623. if (!skeletonAlreadyLoaded) {
  20624. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20625. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20626. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20627. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20628. loadedSkeletonsIds.push(parsedSkeleton.id);
  20629. }
  20630. }
  20631. }
  20632. }
  20633. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20634. meshes.push(mesh);
  20635. }
  20636. }
  20637. // Connecting parents
  20638. for (index = 0; index < scene.meshes.length; index++) {
  20639. var currentMesh = scene.meshes[index];
  20640. if (currentMesh._waitingParentId) {
  20641. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20642. currentMesh._waitingParentId = undefined;
  20643. }
  20644. }
  20645. // freeze world matrix application
  20646. for (index = 0; index < scene.meshes.length; index++) {
  20647. var currentMesh = scene.meshes[index];
  20648. if (currentMesh._waitingFreezeWorldMatrix) {
  20649. currentMesh.freezeWorldMatrix();
  20650. currentMesh._waitingFreezeWorldMatrix = undefined;
  20651. }
  20652. }
  20653. // Particles
  20654. if (parsedData.particleSystems) {
  20655. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20656. var parsedParticleSystem = parsedData.particleSystems[index];
  20657. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20658. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20659. }
  20660. }
  20661. }
  20662. return true;
  20663. },
  20664. load: function (scene, data, rootUrl) {
  20665. var parsedData = JSON.parse(data);
  20666. // Scene
  20667. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20668. scene.autoClear = parsedData.autoClear;
  20669. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20670. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20671. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20672. // Fog
  20673. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20674. scene.fogMode = parsedData.fogMode;
  20675. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20676. scene.fogStart = parsedData.fogStart;
  20677. scene.fogEnd = parsedData.fogEnd;
  20678. scene.fogDensity = parsedData.fogDensity;
  20679. }
  20680. // Lights
  20681. for (var index = 0; index < parsedData.lights.length; index++) {
  20682. var parsedLight = parsedData.lights[index];
  20683. parseLight(parsedLight, scene);
  20684. }
  20685. // Materials
  20686. if (parsedData.materials) {
  20687. for (index = 0; index < parsedData.materials.length; index++) {
  20688. var parsedMaterial = parsedData.materials[index];
  20689. parseMaterial(parsedMaterial, scene, rootUrl);
  20690. }
  20691. }
  20692. if (parsedData.multiMaterials) {
  20693. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20694. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20695. parseMultiMaterial(parsedMultiMaterial, scene);
  20696. }
  20697. }
  20698. // Skeletons
  20699. if (parsedData.skeletons) {
  20700. for (index = 0; index < parsedData.skeletons.length; index++) {
  20701. var parsedSkeleton = parsedData.skeletons[index];
  20702. parseSkeleton(parsedSkeleton, scene);
  20703. }
  20704. }
  20705. // Geometries
  20706. var geometries = parsedData.geometries;
  20707. if (geometries) {
  20708. // Boxes
  20709. var boxes = geometries.boxes;
  20710. if (boxes) {
  20711. for (index = 0; index < boxes.length; index++) {
  20712. var parsedBox = boxes[index];
  20713. parseBox(parsedBox, scene);
  20714. }
  20715. }
  20716. // Spheres
  20717. var spheres = geometries.spheres;
  20718. if (spheres) {
  20719. for (index = 0; index < spheres.length; index++) {
  20720. var parsedSphere = spheres[index];
  20721. parseSphere(parsedSphere, scene);
  20722. }
  20723. }
  20724. // Cylinders
  20725. var cylinders = geometries.cylinders;
  20726. if (cylinders) {
  20727. for (index = 0; index < cylinders.length; index++) {
  20728. var parsedCylinder = cylinders[index];
  20729. parseCylinder(parsedCylinder, scene);
  20730. }
  20731. }
  20732. // Toruses
  20733. var toruses = geometries.toruses;
  20734. if (toruses) {
  20735. for (index = 0; index < toruses.length; index++) {
  20736. var parsedTorus = toruses[index];
  20737. parseTorus(parsedTorus, scene);
  20738. }
  20739. }
  20740. // Grounds
  20741. var grounds = geometries.grounds;
  20742. if (grounds) {
  20743. for (index = 0; index < grounds.length; index++) {
  20744. var parsedGround = grounds[index];
  20745. parseGround(parsedGround, scene);
  20746. }
  20747. }
  20748. // Planes
  20749. var planes = geometries.planes;
  20750. if (planes) {
  20751. for (index = 0; index < planes.length; index++) {
  20752. var parsedPlane = planes[index];
  20753. parsePlane(parsedPlane, scene);
  20754. }
  20755. }
  20756. // TorusKnots
  20757. var torusKnots = geometries.torusKnots;
  20758. if (torusKnots) {
  20759. for (index = 0; index < torusKnots.length; index++) {
  20760. var parsedTorusKnot = torusKnots[index];
  20761. parseTorusKnot(parsedTorusKnot, scene);
  20762. }
  20763. }
  20764. // VertexData
  20765. var vertexData = geometries.vertexData;
  20766. if (vertexData) {
  20767. for (index = 0; index < vertexData.length; index++) {
  20768. var parsedVertexData = vertexData[index];
  20769. parseVertexData(parsedVertexData, scene, rootUrl);
  20770. }
  20771. }
  20772. }
  20773. // Meshes
  20774. for (index = 0; index < parsedData.meshes.length; index++) {
  20775. var parsedMesh = parsedData.meshes[index];
  20776. parseMesh(parsedMesh, scene, rootUrl);
  20777. }
  20778. // Cameras
  20779. for (index = 0; index < parsedData.cameras.length; index++) {
  20780. var parsedCamera = parsedData.cameras[index];
  20781. parseCamera(parsedCamera, scene);
  20782. }
  20783. if (parsedData.activeCameraID) {
  20784. scene.setActiveCameraByID(parsedData.activeCameraID);
  20785. }
  20786. // Browsing all the graph to connect the dots
  20787. for (index = 0; index < scene.cameras.length; index++) {
  20788. var camera = scene.cameras[index];
  20789. if (camera._waitingParentId) {
  20790. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20791. camera._waitingParentId = undefined;
  20792. }
  20793. }
  20794. for (index = 0; index < scene.lights.length; index++) {
  20795. var light = scene.lights[index];
  20796. if (light._waitingParentId) {
  20797. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20798. light._waitingParentId = undefined;
  20799. }
  20800. }
  20801. // Sounds
  20802. if (BABYLON.AudioEngine && parsedData.sounds) {
  20803. for (index = 0; index < parsedData.sounds.length; index++) {
  20804. var parsedSound = parsedData.sounds[index];
  20805. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20806. parseSound(parsedSound, scene, rootUrl);
  20807. }
  20808. else {
  20809. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20810. }
  20811. }
  20812. }
  20813. // Connect parents & children and parse actions
  20814. for (index = 0; index < scene.meshes.length; index++) {
  20815. var mesh = scene.meshes[index];
  20816. if (mesh._waitingParentId) {
  20817. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20818. mesh._waitingParentId = undefined;
  20819. }
  20820. if (mesh._waitingActions) {
  20821. parseActions(mesh._waitingActions, mesh, scene);
  20822. mesh._waitingActions = undefined;
  20823. }
  20824. }
  20825. // freeze world matrix application
  20826. for (index = 0; index < scene.meshes.length; index++) {
  20827. var currentMesh = scene.meshes[index];
  20828. if (currentMesh._waitingFreezeWorldMatrix) {
  20829. currentMesh.freezeWorldMatrix();
  20830. currentMesh._waitingFreezeWorldMatrix = undefined;
  20831. }
  20832. }
  20833. // Particles Systems
  20834. if (parsedData.particleSystems) {
  20835. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20836. var parsedParticleSystem = parsedData.particleSystems[index];
  20837. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20838. }
  20839. }
  20840. // Lens flares
  20841. if (parsedData.lensFlareSystems) {
  20842. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20843. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20844. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20845. }
  20846. }
  20847. // Shadows
  20848. if (parsedData.shadowGenerators) {
  20849. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20850. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20851. parseShadowGenerator(parsedShadowGenerator, scene);
  20852. }
  20853. }
  20854. // Actions (scene)
  20855. if (parsedData.actions) {
  20856. parseActions(parsedData.actions, null, scene);
  20857. }
  20858. // Finish
  20859. return true;
  20860. }
  20861. });
  20862. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20863. })(BABYLON || (BABYLON = {}));
  20864. var BABYLON;
  20865. (function (BABYLON) {
  20866. var SpriteManager = (function () {
  20867. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20869. this.name = name;
  20870. this.cellSize = cellSize;
  20871. this.sprites = new Array();
  20872. this.renderingGroupId = 0;
  20873. this.layerMask = 0x0FFFFFFF;
  20874. this.fogEnabled = true;
  20875. this.isPickable = false;
  20876. this._vertexDeclaration = [4, 4, 4, 4];
  20877. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20878. this._capacity = capacity;
  20879. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20880. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20881. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20882. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20883. this._scene = scene;
  20884. this._scene.spriteManagers.push(this);
  20885. // VBO
  20886. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20887. var indices = [];
  20888. var index = 0;
  20889. for (var count = 0; count < capacity; count++) {
  20890. indices.push(index);
  20891. indices.push(index + 1);
  20892. indices.push(index + 2);
  20893. indices.push(index);
  20894. indices.push(index + 2);
  20895. indices.push(index + 3);
  20896. index += 4;
  20897. }
  20898. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20899. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20900. // Effects
  20901. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20902. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20903. }
  20904. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20905. var arrayOffset = index * 16;
  20906. if (offsetX === 0)
  20907. offsetX = this._epsilon;
  20908. else if (offsetX === 1)
  20909. offsetX = 1 - this._epsilon;
  20910. if (offsetY === 0)
  20911. offsetY = this._epsilon;
  20912. else if (offsetY === 1)
  20913. offsetY = 1 - this._epsilon;
  20914. this._vertices[arrayOffset] = sprite.position.x;
  20915. this._vertices[arrayOffset + 1] = sprite.position.y;
  20916. this._vertices[arrayOffset + 2] = sprite.position.z;
  20917. this._vertices[arrayOffset + 3] = sprite.angle;
  20918. this._vertices[arrayOffset + 4] = sprite.width;
  20919. this._vertices[arrayOffset + 5] = sprite.height;
  20920. this._vertices[arrayOffset + 6] = offsetX;
  20921. this._vertices[arrayOffset + 7] = offsetY;
  20922. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20923. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20924. var offset = (sprite.cellIndex / rowSize) >> 0;
  20925. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20926. this._vertices[arrayOffset + 11] = offset;
  20927. // Color
  20928. this._vertices[arrayOffset + 12] = sprite.color.r;
  20929. this._vertices[arrayOffset + 13] = sprite.color.g;
  20930. this._vertices[arrayOffset + 14] = sprite.color.b;
  20931. this._vertices[arrayOffset + 15] = sprite.color.a;
  20932. };
  20933. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20934. var count = Math.min(this._capacity, this.sprites.length);
  20935. var min = BABYLON.Vector3.Zero();
  20936. var max = BABYLON.Vector3.Zero();
  20937. var distance = Number.MAX_VALUE;
  20938. var currentSprite;
  20939. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20940. var cameraView = camera.getViewMatrix();
  20941. for (var index = 0; index < count; index++) {
  20942. var sprite = this.sprites[index];
  20943. if (!sprite) {
  20944. continue;
  20945. }
  20946. if (predicate) {
  20947. if (!predicate(sprite)) {
  20948. continue;
  20949. }
  20950. }
  20951. else if (!sprite.isPickable) {
  20952. continue;
  20953. }
  20954. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20955. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20956. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20957. if (ray.intersectsBoxMinMax(min, max)) {
  20958. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20959. if (distance > currentDistance) {
  20960. distance = currentDistance;
  20961. currentSprite = sprite;
  20962. if (fastCheck) {
  20963. break;
  20964. }
  20965. }
  20966. }
  20967. }
  20968. if (currentSprite) {
  20969. var result = new BABYLON.PickingInfo();
  20970. result.hit = true;
  20971. result.pickedSprite = currentSprite;
  20972. result.distance = distance;
  20973. return result;
  20974. }
  20975. return null;
  20976. };
  20977. SpriteManager.prototype.render = function () {
  20978. // Check
  20979. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20980. return;
  20981. var engine = this._scene.getEngine();
  20982. var baseSize = this._spriteTexture.getBaseSize();
  20983. // Sprites
  20984. var deltaTime = engine.getDeltaTime();
  20985. var max = Math.min(this._capacity, this.sprites.length);
  20986. var rowSize = baseSize.width / this.cellSize;
  20987. var offset = 0;
  20988. for (var index = 0; index < max; index++) {
  20989. var sprite = this.sprites[index];
  20990. if (!sprite) {
  20991. continue;
  20992. }
  20993. sprite._animate(deltaTime);
  20994. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20995. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20996. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20997. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20998. }
  20999. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21000. // Render
  21001. var effect = this._effectBase;
  21002. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21003. effect = this._effectFog;
  21004. }
  21005. engine.enableEffect(effect);
  21006. var viewMatrix = this._scene.getViewMatrix();
  21007. effect.setTexture("diffuseSampler", this._spriteTexture);
  21008. effect.setMatrix("view", viewMatrix);
  21009. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21010. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21011. // Fog
  21012. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21013. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21014. effect.setColor3("vFogColor", this._scene.fogColor);
  21015. }
  21016. // VBOs
  21017. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21018. // Draw order
  21019. engine.setDepthFunctionToLessOrEqual();
  21020. effect.setBool("alphaTest", true);
  21021. engine.setColorWrite(false);
  21022. engine.draw(true, 0, max * 6);
  21023. engine.setColorWrite(true);
  21024. effect.setBool("alphaTest", false);
  21025. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21026. engine.draw(true, 0, max * 6);
  21027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21028. };
  21029. SpriteManager.prototype.dispose = function () {
  21030. if (this._vertexBuffer) {
  21031. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21032. this._vertexBuffer = null;
  21033. }
  21034. if (this._indexBuffer) {
  21035. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21036. this._indexBuffer = null;
  21037. }
  21038. if (this._spriteTexture) {
  21039. this._spriteTexture.dispose();
  21040. this._spriteTexture = null;
  21041. }
  21042. // Remove from scene
  21043. var index = this._scene.spriteManagers.indexOf(this);
  21044. this._scene.spriteManagers.splice(index, 1);
  21045. // Callback
  21046. if (this.onDispose) {
  21047. this.onDispose();
  21048. }
  21049. };
  21050. return SpriteManager;
  21051. })();
  21052. BABYLON.SpriteManager = SpriteManager;
  21053. })(BABYLON || (BABYLON = {}));
  21054. var BABYLON;
  21055. (function (BABYLON) {
  21056. var Sprite = (function () {
  21057. function Sprite(name, manager) {
  21058. this.name = name;
  21059. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21060. this.width = 1.0;
  21061. this.height = 1.0;
  21062. this.angle = 0;
  21063. this.cellIndex = 0;
  21064. this.invertU = 0;
  21065. this.invertV = 0;
  21066. this.animations = new Array();
  21067. this.isPickable = false;
  21068. this._animationStarted = false;
  21069. this._loopAnimation = false;
  21070. this._fromIndex = 0;
  21071. this._toIndex = 0;
  21072. this._delay = 0;
  21073. this._direction = 1;
  21074. this._frameCount = 0;
  21075. this._time = 0;
  21076. this._manager = manager;
  21077. this._manager.sprites.push(this);
  21078. this.position = BABYLON.Vector3.Zero();
  21079. }
  21080. Object.defineProperty(Sprite.prototype, "size", {
  21081. get: function () {
  21082. return this.width;
  21083. },
  21084. set: function (value) {
  21085. this.width = value;
  21086. this.height = value;
  21087. },
  21088. enumerable: true,
  21089. configurable: true
  21090. });
  21091. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21092. this._fromIndex = from;
  21093. this._toIndex = to;
  21094. this._loopAnimation = loop;
  21095. this._delay = delay;
  21096. this._animationStarted = true;
  21097. this._direction = from < to ? 1 : -1;
  21098. this.cellIndex = from;
  21099. this._time = 0;
  21100. };
  21101. Sprite.prototype.stopAnimation = function () {
  21102. this._animationStarted = false;
  21103. };
  21104. Sprite.prototype._animate = function (deltaTime) {
  21105. if (!this._animationStarted)
  21106. return;
  21107. this._time += deltaTime;
  21108. if (this._time > this._delay) {
  21109. this._time = this._time % this._delay;
  21110. this.cellIndex += this._direction;
  21111. if (this.cellIndex == this._toIndex) {
  21112. if (this._loopAnimation) {
  21113. this.cellIndex = this._fromIndex;
  21114. }
  21115. else {
  21116. this._animationStarted = false;
  21117. if (this.disposeWhenFinishedAnimating) {
  21118. this.dispose();
  21119. }
  21120. }
  21121. }
  21122. }
  21123. };
  21124. Sprite.prototype.dispose = function () {
  21125. for (var i = 0; i < this._manager.sprites.length; i++) {
  21126. if (this._manager.sprites[i] == this) {
  21127. this._manager.sprites.splice(i, 1);
  21128. }
  21129. }
  21130. };
  21131. return Sprite;
  21132. })();
  21133. BABYLON.Sprite = Sprite;
  21134. })(BABYLON || (BABYLON = {}));
  21135. var BABYLON;
  21136. (function (BABYLON) {
  21137. var Layer = (function () {
  21138. function Layer(name, imgUrl, scene, isBackground, color) {
  21139. this.name = name;
  21140. this._vertexDeclaration = [2];
  21141. this._vertexStrideSize = 2 * 4;
  21142. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21143. this.isBackground = isBackground === undefined ? true : isBackground;
  21144. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21145. this._scene = scene;
  21146. this._scene.layers.push(this);
  21147. // VBO
  21148. var vertices = [];
  21149. vertices.push(1, 1);
  21150. vertices.push(-1, 1);
  21151. vertices.push(-1, -1);
  21152. vertices.push(1, -1);
  21153. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21154. // Indices
  21155. var indices = [];
  21156. indices.push(0);
  21157. indices.push(1);
  21158. indices.push(2);
  21159. indices.push(0);
  21160. indices.push(2);
  21161. indices.push(3);
  21162. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21163. // Effects
  21164. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21165. }
  21166. Layer.prototype.render = function () {
  21167. // Check
  21168. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21169. return;
  21170. var engine = this._scene.getEngine();
  21171. // Render
  21172. engine.enableEffect(this._effect);
  21173. engine.setState(false);
  21174. // Texture
  21175. this._effect.setTexture("textureSampler", this.texture);
  21176. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21177. // Color
  21178. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21179. // VBOs
  21180. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21181. // Draw order
  21182. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21183. engine.draw(true, 0, 6);
  21184. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21185. };
  21186. Layer.prototype.dispose = function () {
  21187. if (this._vertexBuffer) {
  21188. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21189. this._vertexBuffer = null;
  21190. }
  21191. if (this._indexBuffer) {
  21192. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21193. this._indexBuffer = null;
  21194. }
  21195. if (this.texture) {
  21196. this.texture.dispose();
  21197. this.texture = null;
  21198. }
  21199. // Remove from scene
  21200. var index = this._scene.layers.indexOf(this);
  21201. this._scene.layers.splice(index, 1);
  21202. // Callback
  21203. if (this.onDispose) {
  21204. this.onDispose();
  21205. }
  21206. };
  21207. return Layer;
  21208. })();
  21209. BABYLON.Layer = Layer;
  21210. })(BABYLON || (BABYLON = {}));
  21211. var BABYLON;
  21212. (function (BABYLON) {
  21213. var Particle = (function () {
  21214. function Particle() {
  21215. this.position = BABYLON.Vector3.Zero();
  21216. this.direction = BABYLON.Vector3.Zero();
  21217. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21218. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21219. this.lifeTime = 1.0;
  21220. this.age = 0;
  21221. this.size = 0;
  21222. this.angle = 0;
  21223. this.angularSpeed = 0;
  21224. }
  21225. Particle.prototype.copyTo = function (other) {
  21226. other.position.copyFrom(this.position);
  21227. other.direction.copyFrom(this.direction);
  21228. other.color.copyFrom(this.color);
  21229. other.colorStep.copyFrom(this.colorStep);
  21230. other.lifeTime = this.lifeTime;
  21231. other.age = this.age;
  21232. other.size = this.size;
  21233. other.angle = this.angle;
  21234. other.angularSpeed = this.angularSpeed;
  21235. };
  21236. return Particle;
  21237. })();
  21238. BABYLON.Particle = Particle;
  21239. })(BABYLON || (BABYLON = {}));
  21240. var BABYLON;
  21241. (function (BABYLON) {
  21242. var randomNumber = function (min, max) {
  21243. if (min === max) {
  21244. return (min);
  21245. }
  21246. var random = Math.random();
  21247. return ((random * (max - min)) + min);
  21248. };
  21249. var ParticleSystem = (function () {
  21250. function ParticleSystem(name, capacity, scene, customEffect) {
  21251. var _this = this;
  21252. this.name = name;
  21253. this.renderingGroupId = 0;
  21254. this.emitter = null;
  21255. this.emitRate = 10;
  21256. this.manualEmitCount = -1;
  21257. this.updateSpeed = 0.01;
  21258. this.targetStopDuration = 0;
  21259. this.disposeOnStop = false;
  21260. this.minEmitPower = 1;
  21261. this.maxEmitPower = 1;
  21262. this.minLifeTime = 1;
  21263. this.maxLifeTime = 1;
  21264. this.minSize = 1;
  21265. this.maxSize = 1;
  21266. this.minAngularSpeed = 0;
  21267. this.maxAngularSpeed = 0;
  21268. this.layerMask = 0x0FFFFFFF;
  21269. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21270. this.forceDepthWrite = false;
  21271. this.gravity = BABYLON.Vector3.Zero();
  21272. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21273. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21274. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21275. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21276. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21277. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21278. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21279. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21280. this.particles = new Array();
  21281. this._vertexDeclaration = [3, 4, 4];
  21282. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21283. this._stockParticles = new Array();
  21284. this._newPartsExcess = 0;
  21285. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21286. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21287. this._scaledDirection = BABYLON.Vector3.Zero();
  21288. this._scaledGravity = BABYLON.Vector3.Zero();
  21289. this._currentRenderId = -1;
  21290. this._started = false;
  21291. this._stopped = false;
  21292. this._actualFrame = 0;
  21293. this.id = name;
  21294. this._capacity = capacity;
  21295. this._scene = scene;
  21296. this._customEffect = customEffect;
  21297. scene.particleSystems.push(this);
  21298. // VBO
  21299. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21300. var indices = [];
  21301. var index = 0;
  21302. for (var count = 0; count < capacity; count++) {
  21303. indices.push(index);
  21304. indices.push(index + 1);
  21305. indices.push(index + 2);
  21306. indices.push(index);
  21307. indices.push(index + 2);
  21308. indices.push(index + 3);
  21309. index += 4;
  21310. }
  21311. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21312. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21313. // Default behaviors
  21314. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21315. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21316. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21317. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21318. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21319. };
  21320. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21321. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21322. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21323. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21325. };
  21326. this.updateFunction = function (particles) {
  21327. for (var index = 0; index < particles.length; index++) {
  21328. var particle = particles[index];
  21329. particle.age += _this._scaledUpdateSpeed;
  21330. if (particle.age >= particle.lifeTime) {
  21331. _this.recycleParticle(particle);
  21332. index--;
  21333. continue;
  21334. }
  21335. else {
  21336. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21337. particle.color.addInPlace(_this._scaledColorStep);
  21338. if (particle.color.a < 0)
  21339. particle.color.a = 0;
  21340. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21341. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21342. particle.position.addInPlace(_this._scaledDirection);
  21343. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21344. particle.direction.addInPlace(_this._scaledGravity);
  21345. }
  21346. }
  21347. };
  21348. }
  21349. ParticleSystem.prototype.recycleParticle = function (particle) {
  21350. var lastParticle = this.particles.pop();
  21351. if (lastParticle !== particle) {
  21352. lastParticle.copyTo(particle);
  21353. this._stockParticles.push(lastParticle);
  21354. }
  21355. };
  21356. ParticleSystem.prototype.getCapacity = function () {
  21357. return this._capacity;
  21358. };
  21359. ParticleSystem.prototype.isAlive = function () {
  21360. return this._alive;
  21361. };
  21362. ParticleSystem.prototype.isStarted = function () {
  21363. return this._started;
  21364. };
  21365. ParticleSystem.prototype.start = function () {
  21366. this._started = true;
  21367. this._stopped = false;
  21368. this._actualFrame = 0;
  21369. };
  21370. ParticleSystem.prototype.stop = function () {
  21371. this._stopped = true;
  21372. };
  21373. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21374. var offset = index * 11;
  21375. this._vertices[offset] = particle.position.x;
  21376. this._vertices[offset + 1] = particle.position.y;
  21377. this._vertices[offset + 2] = particle.position.z;
  21378. this._vertices[offset + 3] = particle.color.r;
  21379. this._vertices[offset + 4] = particle.color.g;
  21380. this._vertices[offset + 5] = particle.color.b;
  21381. this._vertices[offset + 6] = particle.color.a;
  21382. this._vertices[offset + 7] = particle.angle;
  21383. this._vertices[offset + 8] = particle.size;
  21384. this._vertices[offset + 9] = offsetX;
  21385. this._vertices[offset + 10] = offsetY;
  21386. };
  21387. ParticleSystem.prototype._update = function (newParticles) {
  21388. // Update current
  21389. this._alive = this.particles.length > 0;
  21390. this.updateFunction(this.particles);
  21391. // Add new ones
  21392. var worldMatrix;
  21393. if (this.emitter.position) {
  21394. worldMatrix = this.emitter.getWorldMatrix();
  21395. }
  21396. else {
  21397. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21398. }
  21399. for (var index = 0; index < newParticles; index++) {
  21400. if (this.particles.length === this._capacity) {
  21401. break;
  21402. }
  21403. if (this._stockParticles.length !== 0) {
  21404. var particle = this._stockParticles.pop();
  21405. particle.age = 0;
  21406. }
  21407. else {
  21408. particle = new BABYLON.Particle();
  21409. }
  21410. this.particles.push(particle);
  21411. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21412. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21413. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21414. particle.size = randomNumber(this.minSize, this.maxSize);
  21415. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21416. this.startPositionFunction(worldMatrix, particle.position);
  21417. var step = randomNumber(0, 1.0);
  21418. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21419. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21420. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21421. }
  21422. };
  21423. ParticleSystem.prototype._getEffect = function () {
  21424. if (this._customEffect) {
  21425. return this._customEffect;
  21426. }
  21427. ;
  21428. var defines = [];
  21429. if (this._scene.clipPlane) {
  21430. defines.push("#define CLIPPLANE");
  21431. }
  21432. // Effect
  21433. var join = defines.join("\n");
  21434. if (this._cachedDefines !== join) {
  21435. this._cachedDefines = join;
  21436. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21437. }
  21438. return this._effect;
  21439. };
  21440. ParticleSystem.prototype.animate = function () {
  21441. if (!this._started)
  21442. return;
  21443. var effect = this._getEffect();
  21444. // Check
  21445. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21446. return;
  21447. if (this._currentRenderId === this._scene.getRenderId()) {
  21448. return;
  21449. }
  21450. this._currentRenderId = this._scene.getRenderId();
  21451. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21452. // determine the number of particles we need to create
  21453. var emitCout;
  21454. if (this.manualEmitCount > -1) {
  21455. emitCout = this.manualEmitCount;
  21456. this.manualEmitCount = 0;
  21457. }
  21458. else {
  21459. emitCout = this.emitRate;
  21460. }
  21461. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21462. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21463. if (this._newPartsExcess > 1.0) {
  21464. newParticles += this._newPartsExcess >> 0;
  21465. this._newPartsExcess -= this._newPartsExcess >> 0;
  21466. }
  21467. this._alive = false;
  21468. if (!this._stopped) {
  21469. this._actualFrame += this._scaledUpdateSpeed;
  21470. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21471. this.stop();
  21472. }
  21473. else {
  21474. newParticles = 0;
  21475. }
  21476. this._update(newParticles);
  21477. // Stopped?
  21478. if (this._stopped) {
  21479. if (!this._alive) {
  21480. this._started = false;
  21481. if (this.disposeOnStop) {
  21482. this._scene._toBeDisposed.push(this);
  21483. }
  21484. }
  21485. }
  21486. // Update VBO
  21487. var offset = 0;
  21488. for (var index = 0; index < this.particles.length; index++) {
  21489. var particle = this.particles[index];
  21490. this._appendParticleVertex(offset++, particle, 0, 0);
  21491. this._appendParticleVertex(offset++, particle, 1, 0);
  21492. this._appendParticleVertex(offset++, particle, 1, 1);
  21493. this._appendParticleVertex(offset++, particle, 0, 1);
  21494. }
  21495. var engine = this._scene.getEngine();
  21496. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21497. };
  21498. ParticleSystem.prototype.render = function () {
  21499. var effect = this._getEffect();
  21500. // Check
  21501. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21502. return 0;
  21503. var engine = this._scene.getEngine();
  21504. // Render
  21505. engine.enableEffect(effect);
  21506. engine.setState(false);
  21507. var viewMatrix = this._scene.getViewMatrix();
  21508. effect.setTexture("diffuseSampler", this.particleTexture);
  21509. effect.setMatrix("view", viewMatrix);
  21510. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21511. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21512. if (this._scene.clipPlane) {
  21513. var clipPlane = this._scene.clipPlane;
  21514. var invView = viewMatrix.clone();
  21515. invView.invert();
  21516. effect.setMatrix("invView", invView);
  21517. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21518. }
  21519. // VBOs
  21520. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21521. // Draw order
  21522. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21523. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21524. }
  21525. else {
  21526. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21527. }
  21528. if (this.forceDepthWrite) {
  21529. engine.setDepthWrite(true);
  21530. }
  21531. engine.draw(true, 0, this.particles.length * 6);
  21532. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21533. return this.particles.length;
  21534. };
  21535. ParticleSystem.prototype.dispose = function () {
  21536. if (this._vertexBuffer) {
  21537. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21538. this._vertexBuffer = null;
  21539. }
  21540. if (this._indexBuffer) {
  21541. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21542. this._indexBuffer = null;
  21543. }
  21544. if (this.particleTexture) {
  21545. this.particleTexture.dispose();
  21546. this.particleTexture = null;
  21547. }
  21548. // Remove from scene
  21549. var index = this._scene.particleSystems.indexOf(this);
  21550. this._scene.particleSystems.splice(index, 1);
  21551. // Callback
  21552. if (this.onDispose) {
  21553. this.onDispose();
  21554. }
  21555. };
  21556. // Clone
  21557. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21558. var result = new ParticleSystem(name, this._capacity, this._scene);
  21559. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21560. if (newEmitter === undefined) {
  21561. newEmitter = this.emitter;
  21562. }
  21563. result.emitter = newEmitter;
  21564. if (this.particleTexture) {
  21565. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21566. }
  21567. result.start();
  21568. return result;
  21569. };
  21570. // Statics
  21571. ParticleSystem.BLENDMODE_ONEONE = 0;
  21572. ParticleSystem.BLENDMODE_STANDARD = 1;
  21573. return ParticleSystem;
  21574. })();
  21575. BABYLON.ParticleSystem = ParticleSystem;
  21576. })(BABYLON || (BABYLON = {}));
  21577. var BABYLON;
  21578. (function (BABYLON) {
  21579. var AnimationRange = (function () {
  21580. function AnimationRange(name, from, to) {
  21581. this.name = name;
  21582. this.from = from;
  21583. this.to = to;
  21584. }
  21585. return AnimationRange;
  21586. })();
  21587. BABYLON.AnimationRange = AnimationRange;
  21588. var Animation = (function () {
  21589. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21590. this.name = name;
  21591. this.targetProperty = targetProperty;
  21592. this.framePerSecond = framePerSecond;
  21593. this.dataType = dataType;
  21594. this.loopMode = loopMode;
  21595. this._offsetsCache = {};
  21596. this._highLimitsCache = {};
  21597. this._stopped = false;
  21598. this.allowMatricesInterpolation = false;
  21599. this._ranges = new Array();
  21600. this.targetPropertyPath = targetProperty.split(".");
  21601. this.dataType = dataType;
  21602. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21603. }
  21604. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21605. var dataType = undefined;
  21606. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21607. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21608. }
  21609. else if (from instanceof BABYLON.Quaternion) {
  21610. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21611. }
  21612. else if (from instanceof BABYLON.Vector3) {
  21613. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21614. }
  21615. else if (from instanceof BABYLON.Vector2) {
  21616. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21617. }
  21618. else if (from instanceof BABYLON.Color3) {
  21619. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21620. }
  21621. if (dataType == undefined) {
  21622. return null;
  21623. }
  21624. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21625. var keys = [];
  21626. keys.push({ frame: 0, value: from });
  21627. keys.push({ frame: totalFrame, value: to });
  21628. animation.setKeys(keys);
  21629. if (easingFunction !== undefined) {
  21630. animation.setEasingFunction(easingFunction);
  21631. }
  21632. return animation;
  21633. };
  21634. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21635. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21636. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21637. };
  21638. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21639. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21640. node.animations.push(animation);
  21641. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21642. };
  21643. // Methods
  21644. Animation.prototype.createRange = function (name, from, to) {
  21645. this._ranges.push(new AnimationRange(name, from, to));
  21646. };
  21647. Animation.prototype.deleteRange = function (name) {
  21648. for (var index = 0; index < this._ranges.length; index++) {
  21649. if (this._ranges[index].name === name) {
  21650. this._ranges.splice(index, 1);
  21651. return;
  21652. }
  21653. }
  21654. };
  21655. Animation.prototype.getRange = function (name) {
  21656. for (var index = 0; index < this._ranges.length; index++) {
  21657. if (this._ranges[index].name === name) {
  21658. return this._ranges[index];
  21659. }
  21660. }
  21661. return null;
  21662. };
  21663. Animation.prototype.reset = function () {
  21664. this._offsetsCache = {};
  21665. this._highLimitsCache = {};
  21666. this.currentFrame = 0;
  21667. };
  21668. Animation.prototype.isStopped = function () {
  21669. return this._stopped;
  21670. };
  21671. Animation.prototype.getKeys = function () {
  21672. return this._keys;
  21673. };
  21674. Animation.prototype.getEasingFunction = function () {
  21675. return this._easingFunction;
  21676. };
  21677. Animation.prototype.setEasingFunction = function (easingFunction) {
  21678. this._easingFunction = easingFunction;
  21679. };
  21680. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21681. return startValue + (endValue - startValue) * gradient;
  21682. };
  21683. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21684. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21685. };
  21686. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21687. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21688. };
  21689. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21690. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21691. };
  21692. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21693. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21694. };
  21695. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21696. var startScale = new BABYLON.Vector3(0, 0, 0);
  21697. var startRotation = new BABYLON.Quaternion();
  21698. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21699. startValue.decompose(startScale, startRotation, startTranslation);
  21700. var endScale = new BABYLON.Vector3(0, 0, 0);
  21701. var endRotation = new BABYLON.Quaternion();
  21702. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21703. endValue.decompose(endScale, endRotation, endTranslation);
  21704. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21705. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21706. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21707. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21708. return result;
  21709. };
  21710. Animation.prototype.clone = function () {
  21711. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21712. if (this._keys) {
  21713. clone.setKeys(this._keys);
  21714. }
  21715. return clone;
  21716. };
  21717. Animation.prototype.setKeys = function (values) {
  21718. this._keys = values.slice(0);
  21719. this._offsetsCache = {};
  21720. this._highLimitsCache = {};
  21721. };
  21722. Animation.prototype._getKeyValue = function (value) {
  21723. if (typeof value === "function") {
  21724. return value();
  21725. }
  21726. return value;
  21727. };
  21728. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21729. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21730. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21731. }
  21732. this.currentFrame = currentFrame;
  21733. // Try to get a hash to find the right key
  21734. 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));
  21735. if (this._keys[startKey].frame >= currentFrame) {
  21736. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21737. startKey--;
  21738. }
  21739. }
  21740. for (var key = startKey; key < this._keys.length; key++) {
  21741. if (this._keys[key + 1].frame >= currentFrame) {
  21742. var startValue = this._getKeyValue(this._keys[key].value);
  21743. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21744. // gradient : percent of currentFrame between the frame inf and the frame sup
  21745. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21746. // check for easingFunction and correction of gradient
  21747. if (this._easingFunction != null) {
  21748. gradient = this._easingFunction.ease(gradient);
  21749. }
  21750. switch (this.dataType) {
  21751. // Float
  21752. case Animation.ANIMATIONTYPE_FLOAT:
  21753. switch (loopMode) {
  21754. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21755. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21756. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21757. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21758. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21759. }
  21760. break;
  21761. // Quaternion
  21762. case Animation.ANIMATIONTYPE_QUATERNION:
  21763. var quaternion = null;
  21764. switch (loopMode) {
  21765. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21766. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21767. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21768. break;
  21769. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21770. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21771. break;
  21772. }
  21773. return quaternion;
  21774. // Vector3
  21775. case Animation.ANIMATIONTYPE_VECTOR3:
  21776. switch (loopMode) {
  21777. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21778. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21779. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21780. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21781. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21782. }
  21783. // Vector2
  21784. case Animation.ANIMATIONTYPE_VECTOR2:
  21785. switch (loopMode) {
  21786. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21787. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21788. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21789. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21790. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21791. }
  21792. // Color3
  21793. case Animation.ANIMATIONTYPE_COLOR3:
  21794. switch (loopMode) {
  21795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21797. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21799. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21800. }
  21801. // Matrix
  21802. case Animation.ANIMATIONTYPE_MATRIX:
  21803. switch (loopMode) {
  21804. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21805. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21806. if (this.allowMatricesInterpolation) {
  21807. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21808. }
  21809. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21810. return startValue;
  21811. }
  21812. default:
  21813. break;
  21814. }
  21815. break;
  21816. }
  21817. }
  21818. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21819. };
  21820. Animation.prototype.setValue = function (currentValue) {
  21821. // Set value
  21822. if (this.targetPropertyPath.length > 1) {
  21823. var property = this._target[this.targetPropertyPath[0]];
  21824. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21825. property = property[this.targetPropertyPath[index]];
  21826. }
  21827. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21828. }
  21829. else {
  21830. this._target[this.targetPropertyPath[0]] = currentValue;
  21831. }
  21832. if (this._target.markAsDirty) {
  21833. this._target.markAsDirty(this.targetProperty);
  21834. }
  21835. };
  21836. Animation.prototype.goToFrame = function (frame) {
  21837. if (frame < this._keys[0].frame) {
  21838. frame = this._keys[0].frame;
  21839. }
  21840. else if (frame > this._keys[this._keys.length - 1].frame) {
  21841. frame = this._keys[this._keys.length - 1].frame;
  21842. }
  21843. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21844. this.setValue(currentValue);
  21845. };
  21846. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21847. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21848. this._stopped = true;
  21849. return false;
  21850. }
  21851. var returnValue = true;
  21852. // Adding a start key at frame 0 if missing
  21853. if (this._keys[0].frame !== 0) {
  21854. var newKey = { frame: 0, value: this._keys[0].value };
  21855. this._keys.splice(0, 0, newKey);
  21856. }
  21857. // Check limits
  21858. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21859. from = this._keys[0].frame;
  21860. }
  21861. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21862. to = this._keys[this._keys.length - 1].frame;
  21863. }
  21864. // Compute ratio
  21865. var range = to - from;
  21866. var offsetValue;
  21867. // ratio represents the frame delta between from and to
  21868. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21869. var highLimitValue = 0;
  21870. if (ratio > range && !loop) {
  21871. returnValue = false;
  21872. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21873. }
  21874. else {
  21875. // Get max value if required
  21876. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21877. var keyOffset = to.toString() + from.toString();
  21878. if (!this._offsetsCache[keyOffset]) {
  21879. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21880. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21881. switch (this.dataType) {
  21882. // Float
  21883. case Animation.ANIMATIONTYPE_FLOAT:
  21884. this._offsetsCache[keyOffset] = toValue - fromValue;
  21885. break;
  21886. // Quaternion
  21887. case Animation.ANIMATIONTYPE_QUATERNION:
  21888. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21889. break;
  21890. // Vector3
  21891. case Animation.ANIMATIONTYPE_VECTOR3:
  21892. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21893. // Vector2
  21894. case Animation.ANIMATIONTYPE_VECTOR2:
  21895. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21896. // Color3
  21897. case Animation.ANIMATIONTYPE_COLOR3:
  21898. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21899. default:
  21900. break;
  21901. }
  21902. this._highLimitsCache[keyOffset] = toValue;
  21903. }
  21904. highLimitValue = this._highLimitsCache[keyOffset];
  21905. offsetValue = this._offsetsCache[keyOffset];
  21906. }
  21907. }
  21908. if (offsetValue === undefined) {
  21909. switch (this.dataType) {
  21910. // Float
  21911. case Animation.ANIMATIONTYPE_FLOAT:
  21912. offsetValue = 0;
  21913. break;
  21914. // Quaternion
  21915. case Animation.ANIMATIONTYPE_QUATERNION:
  21916. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21917. break;
  21918. // Vector3
  21919. case Animation.ANIMATIONTYPE_VECTOR3:
  21920. offsetValue = BABYLON.Vector3.Zero();
  21921. break;
  21922. // Vector2
  21923. case Animation.ANIMATIONTYPE_VECTOR2:
  21924. offsetValue = BABYLON.Vector2.Zero();
  21925. break;
  21926. // Color3
  21927. case Animation.ANIMATIONTYPE_COLOR3:
  21928. offsetValue = BABYLON.Color3.Black();
  21929. }
  21930. }
  21931. // Compute value
  21932. var repeatCount = (ratio / range) >> 0;
  21933. var currentFrame = returnValue ? from + ratio % range : to;
  21934. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21935. // Set value
  21936. this.setValue(currentValue);
  21937. if (!returnValue) {
  21938. this._stopped = true;
  21939. }
  21940. return returnValue;
  21941. };
  21942. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21943. get: function () {
  21944. return Animation._ANIMATIONTYPE_FLOAT;
  21945. },
  21946. enumerable: true,
  21947. configurable: true
  21948. });
  21949. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21950. get: function () {
  21951. return Animation._ANIMATIONTYPE_VECTOR3;
  21952. },
  21953. enumerable: true,
  21954. configurable: true
  21955. });
  21956. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21957. get: function () {
  21958. return Animation._ANIMATIONTYPE_VECTOR2;
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21964. get: function () {
  21965. return Animation._ANIMATIONTYPE_QUATERNION;
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21971. get: function () {
  21972. return Animation._ANIMATIONTYPE_MATRIX;
  21973. },
  21974. enumerable: true,
  21975. configurable: true
  21976. });
  21977. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21978. get: function () {
  21979. return Animation._ANIMATIONTYPE_COLOR3;
  21980. },
  21981. enumerable: true,
  21982. configurable: true
  21983. });
  21984. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21985. get: function () {
  21986. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21992. get: function () {
  21993. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21999. get: function () {
  22000. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. // Statics
  22006. Animation._ANIMATIONTYPE_FLOAT = 0;
  22007. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22008. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22009. Animation._ANIMATIONTYPE_MATRIX = 3;
  22010. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22011. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22012. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22013. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22014. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22015. return Animation;
  22016. })();
  22017. BABYLON.Animation = Animation;
  22018. })(BABYLON || (BABYLON = {}));
  22019. var BABYLON;
  22020. (function (BABYLON) {
  22021. var Animatable = (function () {
  22022. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22023. if (fromFrame === void 0) { fromFrame = 0; }
  22024. if (toFrame === void 0) { toFrame = 100; }
  22025. if (loopAnimation === void 0) { loopAnimation = false; }
  22026. if (speedRatio === void 0) { speedRatio = 1.0; }
  22027. this.target = target;
  22028. this.fromFrame = fromFrame;
  22029. this.toFrame = toFrame;
  22030. this.loopAnimation = loopAnimation;
  22031. this.speedRatio = speedRatio;
  22032. this.onAnimationEnd = onAnimationEnd;
  22033. this._animations = new Array();
  22034. this._paused = false;
  22035. this.animationStarted = false;
  22036. if (animations) {
  22037. this.appendAnimations(target, animations);
  22038. }
  22039. this._scene = scene;
  22040. scene._activeAnimatables.push(this);
  22041. }
  22042. // Methods
  22043. Animatable.prototype.getAnimations = function () {
  22044. return this._animations;
  22045. };
  22046. Animatable.prototype.appendAnimations = function (target, animations) {
  22047. for (var index = 0; index < animations.length; index++) {
  22048. var animation = animations[index];
  22049. animation._target = target;
  22050. this._animations.push(animation);
  22051. }
  22052. };
  22053. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22054. var animations = this._animations;
  22055. for (var index = 0; index < animations.length; index++) {
  22056. if (animations[index].targetProperty === property) {
  22057. return animations[index];
  22058. }
  22059. }
  22060. return null;
  22061. };
  22062. Animatable.prototype.reset = function () {
  22063. var animations = this._animations;
  22064. for (var index = 0; index < animations.length; index++) {
  22065. animations[index].reset();
  22066. }
  22067. this._localDelayOffset = null;
  22068. this._pausedDelay = null;
  22069. };
  22070. Animatable.prototype.goToFrame = function (frame) {
  22071. var animations = this._animations;
  22072. for (var index = 0; index < animations.length; index++) {
  22073. animations[index].goToFrame(frame);
  22074. }
  22075. };
  22076. Animatable.prototype.pause = function () {
  22077. if (this._paused) {
  22078. return;
  22079. }
  22080. this._paused = true;
  22081. };
  22082. Animatable.prototype.restart = function () {
  22083. this._paused = false;
  22084. };
  22085. Animatable.prototype.stop = function () {
  22086. var index = this._scene._activeAnimatables.indexOf(this);
  22087. if (index > -1) {
  22088. this._scene._activeAnimatables.splice(index, 1);
  22089. }
  22090. if (this.onAnimationEnd) {
  22091. this.onAnimationEnd();
  22092. }
  22093. };
  22094. Animatable.prototype._animate = function (delay) {
  22095. if (this._paused) {
  22096. this.animationStarted = false;
  22097. if (!this._pausedDelay) {
  22098. this._pausedDelay = delay;
  22099. }
  22100. return true;
  22101. }
  22102. if (!this._localDelayOffset) {
  22103. this._localDelayOffset = delay;
  22104. }
  22105. else if (this._pausedDelay) {
  22106. this._localDelayOffset += delay - this._pausedDelay;
  22107. this._pausedDelay = null;
  22108. }
  22109. // Animating
  22110. var running = false;
  22111. var animations = this._animations;
  22112. var index;
  22113. for (index = 0; index < animations.length; index++) {
  22114. var animation = animations[index];
  22115. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22116. running = running || isRunning;
  22117. }
  22118. this.animationStarted = running;
  22119. if (!running) {
  22120. // Remove from active animatables
  22121. index = this._scene._activeAnimatables.indexOf(this);
  22122. this._scene._activeAnimatables.splice(index, 1);
  22123. }
  22124. if (!running && this.onAnimationEnd) {
  22125. this.onAnimationEnd();
  22126. }
  22127. return running;
  22128. };
  22129. return Animatable;
  22130. })();
  22131. BABYLON.Animatable = Animatable;
  22132. })(BABYLON || (BABYLON = {}));
  22133. var BABYLON;
  22134. (function (BABYLON) {
  22135. var EasingFunction = (function () {
  22136. function EasingFunction() {
  22137. // Properties
  22138. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22139. }
  22140. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22141. get: function () {
  22142. return EasingFunction._EASINGMODE_EASEIN;
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22148. get: function () {
  22149. return EasingFunction._EASINGMODE_EASEOUT;
  22150. },
  22151. enumerable: true,
  22152. configurable: true
  22153. });
  22154. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22155. get: function () {
  22156. return EasingFunction._EASINGMODE_EASEINOUT;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22162. var n = Math.min(Math.max(easingMode, 0), 2);
  22163. this._easingMode = n;
  22164. };
  22165. EasingFunction.prototype.getEasingMode = function () {
  22166. return this._easingMode;
  22167. };
  22168. EasingFunction.prototype.easeInCore = function (gradient) {
  22169. throw new Error('You must implement this method');
  22170. };
  22171. EasingFunction.prototype.ease = function (gradient) {
  22172. switch (this._easingMode) {
  22173. case EasingFunction.EASINGMODE_EASEIN:
  22174. return this.easeInCore(gradient);
  22175. case EasingFunction.EASINGMODE_EASEOUT:
  22176. return (1 - this.easeInCore(1 - gradient));
  22177. }
  22178. if (gradient >= 0.5) {
  22179. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22180. }
  22181. return (this.easeInCore(gradient * 2) * 0.5);
  22182. };
  22183. //Statics
  22184. EasingFunction._EASINGMODE_EASEIN = 0;
  22185. EasingFunction._EASINGMODE_EASEOUT = 1;
  22186. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22187. return EasingFunction;
  22188. })();
  22189. BABYLON.EasingFunction = EasingFunction;
  22190. var CircleEase = (function (_super) {
  22191. __extends(CircleEase, _super);
  22192. function CircleEase() {
  22193. _super.apply(this, arguments);
  22194. }
  22195. CircleEase.prototype.easeInCore = function (gradient) {
  22196. gradient = Math.max(0, Math.min(1, gradient));
  22197. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22198. };
  22199. return CircleEase;
  22200. })(EasingFunction);
  22201. BABYLON.CircleEase = CircleEase;
  22202. var BackEase = (function (_super) {
  22203. __extends(BackEase, _super);
  22204. function BackEase(amplitude) {
  22205. if (amplitude === void 0) { amplitude = 1; }
  22206. _super.call(this);
  22207. this.amplitude = amplitude;
  22208. }
  22209. BackEase.prototype.easeInCore = function (gradient) {
  22210. var num = Math.max(0, this.amplitude);
  22211. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22212. };
  22213. return BackEase;
  22214. })(EasingFunction);
  22215. BABYLON.BackEase = BackEase;
  22216. var BounceEase = (function (_super) {
  22217. __extends(BounceEase, _super);
  22218. function BounceEase(bounces, bounciness) {
  22219. if (bounces === void 0) { bounces = 3; }
  22220. if (bounciness === void 0) { bounciness = 2; }
  22221. _super.call(this);
  22222. this.bounces = bounces;
  22223. this.bounciness = bounciness;
  22224. }
  22225. BounceEase.prototype.easeInCore = function (gradient) {
  22226. var y = Math.max(0.0, this.bounces);
  22227. var bounciness = this.bounciness;
  22228. if (bounciness <= 1.0) {
  22229. bounciness = 1.001;
  22230. }
  22231. var num9 = Math.pow(bounciness, y);
  22232. var num5 = 1.0 - bounciness;
  22233. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22234. var num15 = gradient * num4;
  22235. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22236. var num3 = Math.floor(num65);
  22237. var num13 = num3 + 1.0;
  22238. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22239. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22240. var num7 = (num8 + num12) * 0.5;
  22241. var num6 = gradient - num7;
  22242. var num2 = num7 - num8;
  22243. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22244. };
  22245. return BounceEase;
  22246. })(EasingFunction);
  22247. BABYLON.BounceEase = BounceEase;
  22248. var CubicEase = (function (_super) {
  22249. __extends(CubicEase, _super);
  22250. function CubicEase() {
  22251. _super.apply(this, arguments);
  22252. }
  22253. CubicEase.prototype.easeInCore = function (gradient) {
  22254. return (gradient * gradient * gradient);
  22255. };
  22256. return CubicEase;
  22257. })(EasingFunction);
  22258. BABYLON.CubicEase = CubicEase;
  22259. var ElasticEase = (function (_super) {
  22260. __extends(ElasticEase, _super);
  22261. function ElasticEase(oscillations, springiness) {
  22262. if (oscillations === void 0) { oscillations = 3; }
  22263. if (springiness === void 0) { springiness = 3; }
  22264. _super.call(this);
  22265. this.oscillations = oscillations;
  22266. this.springiness = springiness;
  22267. }
  22268. ElasticEase.prototype.easeInCore = function (gradient) {
  22269. var num2;
  22270. var num3 = Math.max(0.0, this.oscillations);
  22271. var num = Math.max(0.0, this.springiness);
  22272. if (num == 0) {
  22273. num2 = gradient;
  22274. }
  22275. else {
  22276. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22277. }
  22278. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22279. };
  22280. return ElasticEase;
  22281. })(EasingFunction);
  22282. BABYLON.ElasticEase = ElasticEase;
  22283. var ExponentialEase = (function (_super) {
  22284. __extends(ExponentialEase, _super);
  22285. function ExponentialEase(exponent) {
  22286. if (exponent === void 0) { exponent = 2; }
  22287. _super.call(this);
  22288. this.exponent = exponent;
  22289. }
  22290. ExponentialEase.prototype.easeInCore = function (gradient) {
  22291. if (this.exponent <= 0) {
  22292. return gradient;
  22293. }
  22294. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22295. };
  22296. return ExponentialEase;
  22297. })(EasingFunction);
  22298. BABYLON.ExponentialEase = ExponentialEase;
  22299. var PowerEase = (function (_super) {
  22300. __extends(PowerEase, _super);
  22301. function PowerEase(power) {
  22302. if (power === void 0) { power = 2; }
  22303. _super.call(this);
  22304. this.power = power;
  22305. }
  22306. PowerEase.prototype.easeInCore = function (gradient) {
  22307. var y = Math.max(0.0, this.power);
  22308. return Math.pow(gradient, y);
  22309. };
  22310. return PowerEase;
  22311. })(EasingFunction);
  22312. BABYLON.PowerEase = PowerEase;
  22313. var QuadraticEase = (function (_super) {
  22314. __extends(QuadraticEase, _super);
  22315. function QuadraticEase() {
  22316. _super.apply(this, arguments);
  22317. }
  22318. QuadraticEase.prototype.easeInCore = function (gradient) {
  22319. return (gradient * gradient);
  22320. };
  22321. return QuadraticEase;
  22322. })(EasingFunction);
  22323. BABYLON.QuadraticEase = QuadraticEase;
  22324. var QuarticEase = (function (_super) {
  22325. __extends(QuarticEase, _super);
  22326. function QuarticEase() {
  22327. _super.apply(this, arguments);
  22328. }
  22329. QuarticEase.prototype.easeInCore = function (gradient) {
  22330. return (gradient * gradient * gradient * gradient);
  22331. };
  22332. return QuarticEase;
  22333. })(EasingFunction);
  22334. BABYLON.QuarticEase = QuarticEase;
  22335. var QuinticEase = (function (_super) {
  22336. __extends(QuinticEase, _super);
  22337. function QuinticEase() {
  22338. _super.apply(this, arguments);
  22339. }
  22340. QuinticEase.prototype.easeInCore = function (gradient) {
  22341. return (gradient * gradient * gradient * gradient * gradient);
  22342. };
  22343. return QuinticEase;
  22344. })(EasingFunction);
  22345. BABYLON.QuinticEase = QuinticEase;
  22346. var SineEase = (function (_super) {
  22347. __extends(SineEase, _super);
  22348. function SineEase() {
  22349. _super.apply(this, arguments);
  22350. }
  22351. SineEase.prototype.easeInCore = function (gradient) {
  22352. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22353. };
  22354. return SineEase;
  22355. })(EasingFunction);
  22356. BABYLON.SineEase = SineEase;
  22357. var BezierCurveEase = (function (_super) {
  22358. __extends(BezierCurveEase, _super);
  22359. function BezierCurveEase(x1, y1, x2, y2) {
  22360. if (x1 === void 0) { x1 = 0; }
  22361. if (y1 === void 0) { y1 = 0; }
  22362. if (x2 === void 0) { x2 = 1; }
  22363. if (y2 === void 0) { y2 = 1; }
  22364. _super.call(this);
  22365. this.x1 = x1;
  22366. this.y1 = y1;
  22367. this.x2 = x2;
  22368. this.y2 = y2;
  22369. }
  22370. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22371. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22372. };
  22373. return BezierCurveEase;
  22374. })(EasingFunction);
  22375. BABYLON.BezierCurveEase = BezierCurveEase;
  22376. })(BABYLON || (BABYLON = {}));
  22377. var BABYLON;
  22378. (function (BABYLON) {
  22379. var Bone = (function (_super) {
  22380. __extends(Bone, _super);
  22381. function Bone(name, skeleton, parentBone, matrix) {
  22382. _super.call(this, name, skeleton.getScene());
  22383. this.name = name;
  22384. this.children = new Array();
  22385. this.animations = new Array();
  22386. this._worldTransform = new BABYLON.Matrix();
  22387. this._absoluteTransform = new BABYLON.Matrix();
  22388. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22389. this._skeleton = skeleton;
  22390. this._matrix = matrix;
  22391. this._baseMatrix = matrix;
  22392. skeleton.bones.push(this);
  22393. if (parentBone) {
  22394. this._parent = parentBone;
  22395. parentBone.children.push(this);
  22396. }
  22397. else {
  22398. this._parent = null;
  22399. }
  22400. this._updateDifferenceMatrix();
  22401. }
  22402. // Members
  22403. Bone.prototype.getParent = function () {
  22404. return this._parent;
  22405. };
  22406. Bone.prototype.getLocalMatrix = function () {
  22407. return this._matrix;
  22408. };
  22409. Bone.prototype.getBaseMatrix = function () {
  22410. return this._baseMatrix;
  22411. };
  22412. Bone.prototype.getWorldMatrix = function () {
  22413. return this._worldTransform;
  22414. };
  22415. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22416. return this._invertedAbsoluteTransform;
  22417. };
  22418. Bone.prototype.getAbsoluteMatrix = function () {
  22419. var matrix = this._matrix.clone();
  22420. var parent = this._parent;
  22421. while (parent) {
  22422. matrix = matrix.multiply(parent.getLocalMatrix());
  22423. parent = parent.getParent();
  22424. }
  22425. return matrix;
  22426. };
  22427. // Methods
  22428. Bone.prototype.updateMatrix = function (matrix) {
  22429. this._matrix = matrix;
  22430. this._skeleton._markAsDirty();
  22431. this._updateDifferenceMatrix();
  22432. };
  22433. Bone.prototype._updateDifferenceMatrix = function () {
  22434. if (this._parent) {
  22435. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22436. }
  22437. else {
  22438. this._absoluteTransform.copyFrom(this._matrix);
  22439. }
  22440. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22441. for (var index = 0; index < this.children.length; index++) {
  22442. this.children[index]._updateDifferenceMatrix();
  22443. }
  22444. };
  22445. Bone.prototype.markAsDirty = function () {
  22446. this._currentRenderId++;
  22447. this._skeleton._markAsDirty();
  22448. };
  22449. return Bone;
  22450. })(BABYLON.Node);
  22451. BABYLON.Bone = Bone;
  22452. })(BABYLON || (BABYLON = {}));
  22453. var BABYLON;
  22454. (function (BABYLON) {
  22455. var Skeleton = (function () {
  22456. function Skeleton(name, id, scene) {
  22457. this.name = name;
  22458. this.id = id;
  22459. this.bones = new Array();
  22460. this._isDirty = true;
  22461. this._identity = BABYLON.Matrix.Identity();
  22462. this._ranges = new Array();
  22463. this.bones = [];
  22464. this._scene = scene;
  22465. scene.skeletons.push(this);
  22466. this.prepare();
  22467. //make sure it will recalculate the matrix next time prepare is called.
  22468. this._isDirty = true;
  22469. }
  22470. // Members
  22471. Skeleton.prototype.getTransformMatrices = function () {
  22472. return this._transformMatrices;
  22473. };
  22474. Skeleton.prototype.getScene = function () {
  22475. return this._scene;
  22476. };
  22477. // Methods
  22478. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22479. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22480. };
  22481. Skeleton.prototype.deleteAnimationRange = function (name) {
  22482. for (var index = 0; index < this._ranges.length; index++) {
  22483. if (this._ranges[index].name === name) {
  22484. this._ranges.splice(index, 1);
  22485. return;
  22486. }
  22487. }
  22488. };
  22489. Skeleton.prototype.getAnimationRange = function (name) {
  22490. for (var index = 0; index < this._ranges.length; index++) {
  22491. if (this._ranges[index].name === name) {
  22492. return this._ranges[index];
  22493. }
  22494. }
  22495. return null;
  22496. };
  22497. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22498. var range = this.getAnimationRange(name);
  22499. if (!range) {
  22500. return null;
  22501. }
  22502. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22503. };
  22504. Skeleton.prototype._markAsDirty = function () {
  22505. this._isDirty = true;
  22506. };
  22507. Skeleton.prototype.prepare = function () {
  22508. if (!this._isDirty) {
  22509. return;
  22510. }
  22511. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22512. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22513. }
  22514. for (var index = 0; index < this.bones.length; index++) {
  22515. var bone = this.bones[index];
  22516. var parentBone = bone.getParent();
  22517. if (parentBone) {
  22518. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22519. }
  22520. else {
  22521. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22522. }
  22523. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22524. }
  22525. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22526. this._isDirty = false;
  22527. this._scene._activeBones += this.bones.length;
  22528. };
  22529. Skeleton.prototype.getAnimatables = function () {
  22530. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22531. this._animatables = [];
  22532. for (var index = 0; index < this.bones.length; index++) {
  22533. this._animatables.push(this.bones[index]);
  22534. }
  22535. }
  22536. return this._animatables;
  22537. };
  22538. Skeleton.prototype.clone = function (name, id) {
  22539. var result = new Skeleton(name, id || name, this._scene);
  22540. for (var index = 0; index < this.bones.length; index++) {
  22541. var source = this.bones[index];
  22542. var parentBone = null;
  22543. if (source.getParent()) {
  22544. var parentIndex = this.bones.indexOf(source.getParent());
  22545. parentBone = result.bones[parentIndex];
  22546. }
  22547. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22548. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22549. }
  22550. return result;
  22551. };
  22552. Skeleton.prototype.dispose = function () {
  22553. // Animations
  22554. this.getScene().stopAnimation(this);
  22555. // Remove from scene
  22556. this.getScene().removeSkeleton(this);
  22557. };
  22558. return Skeleton;
  22559. })();
  22560. BABYLON.Skeleton = Skeleton;
  22561. })(BABYLON || (BABYLON = {}));
  22562. var BABYLON;
  22563. (function (BABYLON) {
  22564. var PostProcess = (function () {
  22565. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22567. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22568. this.name = name;
  22569. this.width = -1;
  22570. this.height = -1;
  22571. this._reusable = false;
  22572. this._textures = new BABYLON.SmartArray(2);
  22573. this._currentRenderTextureInd = 0;
  22574. if (camera != null) {
  22575. this._camera = camera;
  22576. this._scene = camera.getScene();
  22577. camera.attachPostProcess(this);
  22578. this._engine = this._scene.getEngine();
  22579. }
  22580. else {
  22581. this._engine = engine;
  22582. }
  22583. this._renderRatio = ratio;
  22584. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22585. this._reusable = reusable || false;
  22586. this._textureType = textureType;
  22587. this._samplers = samplers || [];
  22588. this._samplers.push("textureSampler");
  22589. this._fragmentUrl = fragmentUrl;
  22590. this._parameters = parameters || [];
  22591. this.updateEffect(defines);
  22592. }
  22593. PostProcess.prototype.updateEffect = function (defines) {
  22594. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22595. };
  22596. PostProcess.prototype.isReusable = function () {
  22597. return this._reusable;
  22598. };
  22599. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22600. camera = camera || this._camera;
  22601. var scene = camera.getScene();
  22602. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22603. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22604. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22605. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22606. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22607. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22608. if (this._textures.length > 0) {
  22609. for (var i = 0; i < this._textures.length; i++) {
  22610. this._engine._releaseTexture(this._textures.data[i]);
  22611. }
  22612. this._textures.reset();
  22613. }
  22614. this.width = desiredWidth;
  22615. this.height = desiredHeight;
  22616. 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 }));
  22617. if (this._reusable) {
  22618. 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 }));
  22619. }
  22620. if (this.onSizeChanged) {
  22621. this.onSizeChanged();
  22622. }
  22623. }
  22624. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22625. if (this.onActivate) {
  22626. this.onActivate(camera);
  22627. }
  22628. // Clear
  22629. if (this.clearColor) {
  22630. this._engine.clear(this.clearColor, true, true);
  22631. }
  22632. else {
  22633. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22634. }
  22635. if (this._reusable) {
  22636. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22637. }
  22638. };
  22639. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22640. get: function () {
  22641. return this._effect.isSupported;
  22642. },
  22643. enumerable: true,
  22644. configurable: true
  22645. });
  22646. PostProcess.prototype.apply = function () {
  22647. // Check
  22648. if (!this._effect.isReady())
  22649. return null;
  22650. // States
  22651. this._engine.enableEffect(this._effect);
  22652. this._engine.setState(false);
  22653. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22654. this._engine.setDepthBuffer(false);
  22655. this._engine.setDepthWrite(false);
  22656. // Texture
  22657. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22658. // Parameters
  22659. if (this.onApply) {
  22660. this.onApply(this._effect);
  22661. }
  22662. return this._effect;
  22663. };
  22664. PostProcess.prototype.dispose = function (camera) {
  22665. camera = camera || this._camera;
  22666. if (this._textures.length > 0) {
  22667. for (var i = 0; i < this._textures.length; i++) {
  22668. this._engine._releaseTexture(this._textures.data[i]);
  22669. }
  22670. this._textures.reset();
  22671. }
  22672. if (!camera) {
  22673. return;
  22674. }
  22675. camera.detachPostProcess(this);
  22676. var index = camera._postProcesses.indexOf(this);
  22677. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22678. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22679. }
  22680. };
  22681. return PostProcess;
  22682. })();
  22683. BABYLON.PostProcess = PostProcess;
  22684. })(BABYLON || (BABYLON = {}));
  22685. var BABYLON;
  22686. (function (BABYLON) {
  22687. var PostProcessManager = (function () {
  22688. function PostProcessManager(scene) {
  22689. this._vertexDeclaration = [2];
  22690. this._vertexStrideSize = 2 * 4;
  22691. this._scene = scene;
  22692. }
  22693. PostProcessManager.prototype._prepareBuffers = function () {
  22694. if (this._vertexBuffer) {
  22695. return;
  22696. }
  22697. // VBO
  22698. var vertices = [];
  22699. vertices.push(1, 1);
  22700. vertices.push(-1, 1);
  22701. vertices.push(-1, -1);
  22702. vertices.push(1, -1);
  22703. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22704. // Indices
  22705. var indices = [];
  22706. indices.push(0);
  22707. indices.push(1);
  22708. indices.push(2);
  22709. indices.push(0);
  22710. indices.push(2);
  22711. indices.push(3);
  22712. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22713. };
  22714. // Methods
  22715. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22716. var postProcesses = this._scene.activeCamera._postProcesses;
  22717. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22718. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22719. return false;
  22720. }
  22721. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22722. return true;
  22723. };
  22724. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22725. var engine = this._scene.getEngine();
  22726. for (var index = 0; index < postProcesses.length; index++) {
  22727. if (index < postProcesses.length - 1) {
  22728. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22729. }
  22730. else {
  22731. if (targetTexture) {
  22732. engine.bindFramebuffer(targetTexture);
  22733. }
  22734. else {
  22735. engine.restoreDefaultFramebuffer();
  22736. }
  22737. }
  22738. var pp = postProcesses[index];
  22739. var effect = pp.apply();
  22740. if (effect) {
  22741. if (pp.onBeforeRender) {
  22742. pp.onBeforeRender(effect);
  22743. }
  22744. // VBOs
  22745. this._prepareBuffers();
  22746. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22747. // Draw order
  22748. engine.draw(true, 0, 6);
  22749. if (pp.onAfterRender) {
  22750. pp.onAfterRender(effect);
  22751. }
  22752. }
  22753. }
  22754. // Restore depth buffer
  22755. engine.setDepthBuffer(true);
  22756. engine.setDepthWrite(true);
  22757. };
  22758. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22759. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22760. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22761. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22762. return;
  22763. }
  22764. var engine = this._scene.getEngine();
  22765. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22766. if (index < postProcessesTakenIndices.length - 1) {
  22767. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22768. }
  22769. else {
  22770. if (targetTexture) {
  22771. engine.bindFramebuffer(targetTexture, faceIndex);
  22772. }
  22773. else {
  22774. engine.restoreDefaultFramebuffer();
  22775. }
  22776. }
  22777. if (doNotPresent) {
  22778. break;
  22779. }
  22780. var pp = postProcesses[postProcessesTakenIndices[index]];
  22781. var effect = pp.apply();
  22782. if (effect) {
  22783. if (pp.onBeforeRender) {
  22784. pp.onBeforeRender(effect);
  22785. }
  22786. // VBOs
  22787. this._prepareBuffers();
  22788. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22789. // Draw order
  22790. engine.draw(true, 0, 6);
  22791. if (pp.onAfterRender) {
  22792. pp.onAfterRender(effect);
  22793. }
  22794. }
  22795. }
  22796. // Restore depth buffer
  22797. engine.setDepthBuffer(true);
  22798. engine.setDepthWrite(true);
  22799. };
  22800. PostProcessManager.prototype.dispose = function () {
  22801. if (this._vertexBuffer) {
  22802. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22803. this._vertexBuffer = null;
  22804. }
  22805. if (this._indexBuffer) {
  22806. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22807. this._indexBuffer = null;
  22808. }
  22809. };
  22810. return PostProcessManager;
  22811. })();
  22812. BABYLON.PostProcessManager = PostProcessManager;
  22813. })(BABYLON || (BABYLON = {}));
  22814. var BABYLON;
  22815. (function (BABYLON) {
  22816. var PassPostProcess = (function (_super) {
  22817. __extends(PassPostProcess, _super);
  22818. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22819. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22820. }
  22821. return PassPostProcess;
  22822. })(BABYLON.PostProcess);
  22823. BABYLON.PassPostProcess = PassPostProcess;
  22824. })(BABYLON || (BABYLON = {}));
  22825. var BABYLON;
  22826. (function (BABYLON) {
  22827. var PhysicsEngine = (function () {
  22828. function PhysicsEngine(plugin) {
  22829. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22830. }
  22831. PhysicsEngine.prototype._initialize = function (gravity) {
  22832. this._currentPlugin.initialize();
  22833. this._setGravity(gravity);
  22834. };
  22835. PhysicsEngine.prototype._runOneStep = function (delta) {
  22836. if (delta > 0.1) {
  22837. delta = 0.1;
  22838. }
  22839. else if (delta <= 0) {
  22840. delta = 1.0 / 60.0;
  22841. }
  22842. this._currentPlugin.runOneStep(delta);
  22843. };
  22844. PhysicsEngine.prototype._setGravity = function (gravity) {
  22845. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22846. this._currentPlugin.setGravity(this.gravity);
  22847. };
  22848. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22849. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22850. };
  22851. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22852. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22853. };
  22854. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22855. this._currentPlugin.unregisterMesh(mesh);
  22856. };
  22857. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22858. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22859. };
  22860. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22861. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22862. };
  22863. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22864. this._currentPlugin.updateBodyPosition(mesh);
  22865. };
  22866. PhysicsEngine.prototype.dispose = function () {
  22867. this._currentPlugin.dispose();
  22868. };
  22869. PhysicsEngine.prototype.isSupported = function () {
  22870. return this._currentPlugin.isSupported();
  22871. };
  22872. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22873. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22874. };
  22875. // Statics
  22876. PhysicsEngine.NoImpostor = 0;
  22877. PhysicsEngine.SphereImpostor = 1;
  22878. PhysicsEngine.BoxImpostor = 2;
  22879. PhysicsEngine.PlaneImpostor = 3;
  22880. PhysicsEngine.MeshImpostor = 4;
  22881. PhysicsEngine.CapsuleImpostor = 5;
  22882. PhysicsEngine.ConeImpostor = 6;
  22883. PhysicsEngine.CylinderImpostor = 7;
  22884. PhysicsEngine.ConvexHullImpostor = 8;
  22885. PhysicsEngine.HeightmapImpostor = 9;
  22886. PhysicsEngine.Epsilon = 0.001;
  22887. return PhysicsEngine;
  22888. })();
  22889. BABYLON.PhysicsEngine = PhysicsEngine;
  22890. })(BABYLON || (BABYLON = {}));
  22891. var BABYLON;
  22892. (function (BABYLON) {
  22893. var VertexData = (function () {
  22894. function VertexData() {
  22895. }
  22896. VertexData.prototype.set = function (data, kind) {
  22897. switch (kind) {
  22898. case BABYLON.VertexBuffer.PositionKind:
  22899. this.positions = data;
  22900. break;
  22901. case BABYLON.VertexBuffer.NormalKind:
  22902. this.normals = data;
  22903. break;
  22904. case BABYLON.VertexBuffer.UVKind:
  22905. this.uvs = data;
  22906. break;
  22907. case BABYLON.VertexBuffer.UV2Kind:
  22908. this.uvs2 = data;
  22909. break;
  22910. case BABYLON.VertexBuffer.UV3Kind:
  22911. this.uvs3 = data;
  22912. break;
  22913. case BABYLON.VertexBuffer.UV4Kind:
  22914. this.uvs4 = data;
  22915. break;
  22916. case BABYLON.VertexBuffer.UV5Kind:
  22917. this.uvs5 = data;
  22918. break;
  22919. case BABYLON.VertexBuffer.UV6Kind:
  22920. this.uvs6 = data;
  22921. break;
  22922. case BABYLON.VertexBuffer.ColorKind:
  22923. this.colors = data;
  22924. break;
  22925. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22926. this.matricesIndices = data;
  22927. break;
  22928. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22929. this.matricesWeights = data;
  22930. break;
  22931. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22932. this.matricesIndicesExtra = data;
  22933. break;
  22934. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22935. this.matricesWeightsExtra = data;
  22936. break;
  22937. }
  22938. };
  22939. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22940. this._applyTo(mesh, updatable);
  22941. };
  22942. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22943. this._applyTo(geometry, updatable);
  22944. };
  22945. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22946. this._update(mesh);
  22947. };
  22948. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22949. this._update(geometry);
  22950. };
  22951. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22952. if (this.positions) {
  22953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22954. }
  22955. if (this.normals) {
  22956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22957. }
  22958. if (this.uvs) {
  22959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22960. }
  22961. if (this.uvs2) {
  22962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22963. }
  22964. if (this.uvs3) {
  22965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22966. }
  22967. if (this.uvs4) {
  22968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22969. }
  22970. if (this.uvs5) {
  22971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22972. }
  22973. if (this.uvs6) {
  22974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22975. }
  22976. if (this.colors) {
  22977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22978. }
  22979. if (this.matricesIndices) {
  22980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22981. }
  22982. if (this.matricesWeights) {
  22983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22984. }
  22985. if (this.matricesIndicesExtra) {
  22986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22987. }
  22988. if (this.matricesWeightsExtra) {
  22989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22990. }
  22991. if (this.indices) {
  22992. meshOrGeometry.setIndices(this.indices);
  22993. }
  22994. };
  22995. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22996. if (this.positions) {
  22997. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22998. }
  22999. if (this.normals) {
  23000. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23001. }
  23002. if (this.uvs) {
  23003. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23004. }
  23005. if (this.uvs2) {
  23006. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23007. }
  23008. if (this.uvs3) {
  23009. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23010. }
  23011. if (this.uvs4) {
  23012. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23013. }
  23014. if (this.uvs5) {
  23015. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23016. }
  23017. if (this.uvs6) {
  23018. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23019. }
  23020. if (this.colors) {
  23021. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23022. }
  23023. if (this.matricesIndices) {
  23024. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23025. }
  23026. if (this.matricesWeights) {
  23027. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23028. }
  23029. if (this.matricesIndicesExtra) {
  23030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23031. }
  23032. if (this.matricesWeightsExtra) {
  23033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23034. }
  23035. if (this.indices) {
  23036. meshOrGeometry.setIndices(this.indices);
  23037. }
  23038. };
  23039. VertexData.prototype.transform = function (matrix) {
  23040. var transformed = BABYLON.Vector3.Zero();
  23041. var index;
  23042. if (this.positions) {
  23043. var position = BABYLON.Vector3.Zero();
  23044. for (index = 0; index < this.positions.length; index += 3) {
  23045. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23046. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23047. this.positions[index] = transformed.x;
  23048. this.positions[index + 1] = transformed.y;
  23049. this.positions[index + 2] = transformed.z;
  23050. }
  23051. }
  23052. if (this.normals) {
  23053. var normal = BABYLON.Vector3.Zero();
  23054. for (index = 0; index < this.normals.length; index += 3) {
  23055. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23056. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23057. this.normals[index] = transformed.x;
  23058. this.normals[index + 1] = transformed.y;
  23059. this.normals[index + 2] = transformed.z;
  23060. }
  23061. }
  23062. };
  23063. VertexData.prototype.merge = function (other) {
  23064. var index;
  23065. if (other.indices) {
  23066. if (!this.indices) {
  23067. this.indices = [];
  23068. }
  23069. var offset = this.positions ? this.positions.length / 3 : 0;
  23070. for (index = 0; index < other.indices.length; index++) {
  23071. this.indices.push(other.indices[index] + offset);
  23072. }
  23073. }
  23074. if (other.positions) {
  23075. if (!this.positions) {
  23076. this.positions = [];
  23077. }
  23078. for (index = 0; index < other.positions.length; index++) {
  23079. this.positions.push(other.positions[index]);
  23080. }
  23081. }
  23082. if (other.normals) {
  23083. if (!this.normals) {
  23084. this.normals = [];
  23085. }
  23086. for (index = 0; index < other.normals.length; index++) {
  23087. this.normals.push(other.normals[index]);
  23088. }
  23089. }
  23090. if (other.uvs) {
  23091. if (!this.uvs) {
  23092. this.uvs = [];
  23093. }
  23094. for (index = 0; index < other.uvs.length; index++) {
  23095. this.uvs.push(other.uvs[index]);
  23096. }
  23097. }
  23098. if (other.uvs2) {
  23099. if (!this.uvs2) {
  23100. this.uvs2 = [];
  23101. }
  23102. for (index = 0; index < other.uvs2.length; index++) {
  23103. this.uvs2.push(other.uvs2[index]);
  23104. }
  23105. }
  23106. if (other.uvs3) {
  23107. if (!this.uvs3) {
  23108. this.uvs3 = [];
  23109. }
  23110. for (index = 0; index < other.uvs3.length; index++) {
  23111. this.uvs3.push(other.uvs3[index]);
  23112. }
  23113. }
  23114. if (other.uvs4) {
  23115. if (!this.uvs4) {
  23116. this.uvs4 = [];
  23117. }
  23118. for (index = 0; index < other.uvs4.length; index++) {
  23119. this.uvs4.push(other.uvs4[index]);
  23120. }
  23121. }
  23122. if (other.uvs5) {
  23123. if (!this.uvs5) {
  23124. this.uvs5 = [];
  23125. }
  23126. for (index = 0; index < other.uvs5.length; index++) {
  23127. this.uvs5.push(other.uvs5[index]);
  23128. }
  23129. }
  23130. if (other.uvs6) {
  23131. if (!this.uvs6) {
  23132. this.uvs6 = [];
  23133. }
  23134. for (index = 0; index < other.uvs6.length; index++) {
  23135. this.uvs6.push(other.uvs6[index]);
  23136. }
  23137. }
  23138. if (other.matricesIndices) {
  23139. if (!this.matricesIndices) {
  23140. this.matricesIndices = [];
  23141. }
  23142. for (index = 0; index < other.matricesIndices.length; index++) {
  23143. this.matricesIndices.push(other.matricesIndices[index]);
  23144. }
  23145. }
  23146. if (other.matricesWeights) {
  23147. if (!this.matricesWeights) {
  23148. this.matricesWeights = [];
  23149. }
  23150. for (index = 0; index < other.matricesWeights.length; index++) {
  23151. this.matricesWeights.push(other.matricesWeights[index]);
  23152. }
  23153. }
  23154. if (other.matricesIndicesExtra) {
  23155. if (!this.matricesIndicesExtra) {
  23156. this.matricesIndicesExtra = [];
  23157. }
  23158. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  23159. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  23160. }
  23161. }
  23162. if (other.matricesWeightsExtra) {
  23163. if (!this.matricesWeightsExtra) {
  23164. this.matricesWeightsExtra = [];
  23165. }
  23166. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  23167. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  23168. }
  23169. }
  23170. if (other.colors) {
  23171. if (!this.colors) {
  23172. this.colors = [];
  23173. }
  23174. for (index = 0; index < other.colors.length; index++) {
  23175. this.colors.push(other.colors[index]);
  23176. }
  23177. }
  23178. };
  23179. // Statics
  23180. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23181. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23182. };
  23183. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23184. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23185. };
  23186. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23187. var result = new VertexData();
  23188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23189. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23190. }
  23191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23192. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23193. }
  23194. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23195. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23196. }
  23197. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23198. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23199. }
  23200. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23201. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23202. }
  23203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23204. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23205. }
  23206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23207. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23208. }
  23209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23210. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23211. }
  23212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23213. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23214. }
  23215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23216. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23217. }
  23218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23219. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23220. }
  23221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23222. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23223. }
  23224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23225. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23226. }
  23227. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23228. return result;
  23229. };
  23230. VertexData.CreateRibbon = function (options) {
  23231. var pathArray = options.pathArray;
  23232. var closeArray = options.closeArray || false;
  23233. var closePath = options.closePath || false;
  23234. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23235. var offset = options.offset || defaultOffset;
  23236. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23238. var positions = [];
  23239. var indices = [];
  23240. var normals = [];
  23241. var uvs = [];
  23242. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23243. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23244. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23245. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23246. var minlg; // minimal length among all paths from pathArray
  23247. var lg = []; // array of path lengths : nb of vertex per path
  23248. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23249. var p; // path iterator
  23250. var i; // point iterator
  23251. var j; // point iterator
  23252. // if single path in pathArray
  23253. if (pathArray.length < 2) {
  23254. var ar1 = [];
  23255. var ar2 = [];
  23256. for (i = 0; i < pathArray[0].length - offset; i++) {
  23257. ar1.push(pathArray[0][i]);
  23258. ar2.push(pathArray[0][i + offset]);
  23259. }
  23260. pathArray = [ar1, ar2];
  23261. }
  23262. // positions and horizontal distances (u)
  23263. var idc = 0;
  23264. var closePathCorr = (closePath) ? 1 : 0;
  23265. var path;
  23266. var l;
  23267. minlg = pathArray[0].length;
  23268. var vectlg;
  23269. var dist;
  23270. for (p = 0; p < pathArray.length; p++) {
  23271. uTotalDistance[p] = 0;
  23272. us[p] = [0];
  23273. path = pathArray[p];
  23274. l = path.length;
  23275. minlg = (minlg < l) ? minlg : l;
  23276. j = 0;
  23277. while (j < l) {
  23278. positions.push(path[j].x, path[j].y, path[j].z);
  23279. if (j > 0) {
  23280. vectlg = path[j].subtract(path[j - 1]).length();
  23281. dist = vectlg + uTotalDistance[p];
  23282. us[p].push(dist);
  23283. uTotalDistance[p] = dist;
  23284. }
  23285. j++;
  23286. }
  23287. if (closePath) {
  23288. j--;
  23289. positions.push(path[0].x, path[0].y, path[0].z);
  23290. vectlg = path[j].subtract(path[0]).length();
  23291. dist = vectlg + uTotalDistance[p];
  23292. us[p].push(dist);
  23293. uTotalDistance[p] = dist;
  23294. }
  23295. lg[p] = l + closePathCorr;
  23296. idx[p] = idc;
  23297. idc += (l + closePathCorr);
  23298. }
  23299. // vertical distances (v)
  23300. var path1;
  23301. var path2;
  23302. var vertex1;
  23303. var vertex2;
  23304. for (i = 0; i < minlg + closePathCorr; i++) {
  23305. vTotalDistance[i] = 0;
  23306. vs[i] = [0];
  23307. for (p = 0; p < pathArray.length - 1; p++) {
  23308. path1 = pathArray[p];
  23309. path2 = pathArray[p + 1];
  23310. if (i === minlg) {
  23311. vertex1 = path1[0];
  23312. vertex2 = path2[0];
  23313. }
  23314. else {
  23315. vertex1 = path1[i];
  23316. vertex2 = path2[i];
  23317. }
  23318. vectlg = vertex2.subtract(vertex1).length();
  23319. dist = vectlg + vTotalDistance[i];
  23320. vs[i].push(dist);
  23321. vTotalDistance[i] = dist;
  23322. }
  23323. if (closeArray) {
  23324. path1 = pathArray[p];
  23325. path2 = pathArray[0];
  23326. if (i === minlg) {
  23327. vertex2 = path2[0];
  23328. }
  23329. vectlg = vertex2.subtract(vertex1).length();
  23330. dist = vectlg + vTotalDistance[i];
  23331. vTotalDistance[i] = dist;
  23332. }
  23333. }
  23334. // uvs
  23335. var u;
  23336. var v;
  23337. for (p = 0; p < pathArray.length; p++) {
  23338. for (i = 0; i < minlg + closePathCorr; i++) {
  23339. u = us[p][i] / uTotalDistance[p];
  23340. v = vs[i][p] / vTotalDistance[i];
  23341. uvs.push(u, v);
  23342. }
  23343. }
  23344. // indices
  23345. p = 0; // path index
  23346. var pi = 0; // positions array index
  23347. var l1 = lg[p] - 1; // path1 length
  23348. var l2 = lg[p + 1] - 1; // path2 length
  23349. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23350. var shft = idx[1] - idx[0]; // shift
  23351. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23352. while (pi <= min && p < path1nb) {
  23353. // 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
  23354. indices.push(pi, pi + shft, pi + 1);
  23355. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23356. pi += 1;
  23357. if (pi === min) {
  23358. p++;
  23359. if (p === lg.length - 1) {
  23360. shft = idx[0] - idx[p];
  23361. l1 = lg[p] - 1;
  23362. l2 = lg[0] - 1;
  23363. }
  23364. else {
  23365. shft = idx[p + 1] - idx[p];
  23366. l1 = lg[p] - 1;
  23367. l2 = lg[p + 1] - 1;
  23368. }
  23369. pi = idx[p];
  23370. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23371. }
  23372. }
  23373. // normals
  23374. VertexData.ComputeNormals(positions, indices, normals);
  23375. if (closePath) {
  23376. var indexFirst = 0;
  23377. var indexLast = 0;
  23378. for (p = 0; p < pathArray.length; p++) {
  23379. indexFirst = idx[p] * 3;
  23380. if (p + 1 < pathArray.length) {
  23381. indexLast = (idx[p + 1] - 1) * 3;
  23382. }
  23383. else {
  23384. indexLast = normals.length - 3;
  23385. }
  23386. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23387. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23388. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23389. normals[indexLast] = normals[indexFirst];
  23390. normals[indexLast + 1] = normals[indexFirst + 1];
  23391. normals[indexLast + 2] = normals[indexFirst + 2];
  23392. }
  23393. }
  23394. // sides
  23395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23396. // Result
  23397. var vertexData = new VertexData();
  23398. vertexData.indices = indices;
  23399. vertexData.positions = positions;
  23400. vertexData.normals = normals;
  23401. vertexData.uvs = uvs;
  23402. if (closePath) {
  23403. vertexData._idx = idx;
  23404. }
  23405. return vertexData;
  23406. };
  23407. VertexData.CreateBox = function (options) {
  23408. var normalsSource = [
  23409. new BABYLON.Vector3(0, 0, 1),
  23410. new BABYLON.Vector3(0, 0, -1),
  23411. new BABYLON.Vector3(1, 0, 0),
  23412. new BABYLON.Vector3(-1, 0, 0),
  23413. new BABYLON.Vector3(0, 1, 0),
  23414. new BABYLON.Vector3(0, -1, 0)
  23415. ];
  23416. var indices = [];
  23417. var positions = [];
  23418. var normals = [];
  23419. var uvs = [];
  23420. var width = options.width || options.size || 1;
  23421. var height = options.height || options.size || 1;
  23422. var depth = options.depth || options.size || 1;
  23423. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23424. var faceUV = options.faceUV || new Array(6);
  23425. var faceColors = options.faceColors;
  23426. var colors = [];
  23427. // default face colors and UV if undefined
  23428. for (var f = 0; f < 6; f++) {
  23429. if (faceUV[f] === undefined) {
  23430. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23431. }
  23432. if (faceColors && faceColors[f] === undefined) {
  23433. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23434. }
  23435. }
  23436. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23437. // Create each face in turn.
  23438. for (var index = 0; index < normalsSource.length; index++) {
  23439. var normal = normalsSource[index];
  23440. // Get two vectors perpendicular to the face normal and to each other.
  23441. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23442. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23443. // Six indices (two triangles) per face.
  23444. var verticesLength = positions.length / 3;
  23445. indices.push(verticesLength);
  23446. indices.push(verticesLength + 1);
  23447. indices.push(verticesLength + 2);
  23448. indices.push(verticesLength);
  23449. indices.push(verticesLength + 2);
  23450. indices.push(verticesLength + 3);
  23451. // Four vertices per face.
  23452. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23453. positions.push(vertex.x, vertex.y, vertex.z);
  23454. normals.push(normal.x, normal.y, normal.z);
  23455. uvs.push(faceUV[index].z, faceUV[index].w);
  23456. if (faceColors) {
  23457. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23458. }
  23459. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23460. positions.push(vertex.x, vertex.y, vertex.z);
  23461. normals.push(normal.x, normal.y, normal.z);
  23462. uvs.push(faceUV[index].x, faceUV[index].w);
  23463. if (faceColors) {
  23464. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23465. }
  23466. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23467. positions.push(vertex.x, vertex.y, vertex.z);
  23468. normals.push(normal.x, normal.y, normal.z);
  23469. uvs.push(faceUV[index].x, faceUV[index].y);
  23470. if (faceColors) {
  23471. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23472. }
  23473. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23474. positions.push(vertex.x, vertex.y, vertex.z);
  23475. normals.push(normal.x, normal.y, normal.z);
  23476. uvs.push(faceUV[index].z, faceUV[index].y);
  23477. if (faceColors) {
  23478. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23479. }
  23480. }
  23481. // sides
  23482. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23483. // Result
  23484. var vertexData = new VertexData();
  23485. vertexData.indices = indices;
  23486. vertexData.positions = positions;
  23487. vertexData.normals = normals;
  23488. vertexData.uvs = uvs;
  23489. if (faceColors) {
  23490. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23491. vertexData.colors = totalColors;
  23492. }
  23493. return vertexData;
  23494. };
  23495. VertexData.CreateSphere = function (options) {
  23496. var segments = options.segments || 32;
  23497. var diameterX = options.diameterX || options.diameter || 1;
  23498. var diameterY = options.diameterY || options.diameter || 1;
  23499. var diameterZ = options.diameterZ || options.diameter || 1;
  23500. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23501. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23502. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23503. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23504. var totalZRotationSteps = 2 + segments;
  23505. var totalYRotationSteps = 2 * totalZRotationSteps;
  23506. var indices = [];
  23507. var positions = [];
  23508. var normals = [];
  23509. var uvs = [];
  23510. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23511. var normalizedZ = zRotationStep / totalZRotationSteps;
  23512. var angleZ = normalizedZ * Math.PI * slice;
  23513. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23514. var normalizedY = yRotationStep / totalYRotationSteps;
  23515. var angleY = normalizedY * Math.PI * 2 * arc;
  23516. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23517. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23518. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23519. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23520. var vertex = complete.multiply(radius);
  23521. var normal = BABYLON.Vector3.Normalize(vertex);
  23522. positions.push(vertex.x, vertex.y, vertex.z);
  23523. normals.push(normal.x, normal.y, normal.z);
  23524. uvs.push(normalizedY, normalizedZ);
  23525. }
  23526. if (zRotationStep > 0) {
  23527. var verticesCount = positions.length / 3;
  23528. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23529. indices.push((firstIndex));
  23530. indices.push((firstIndex + 1));
  23531. indices.push(firstIndex + totalYRotationSteps + 1);
  23532. indices.push((firstIndex + totalYRotationSteps + 1));
  23533. indices.push((firstIndex + 1));
  23534. indices.push((firstIndex + totalYRotationSteps + 2));
  23535. }
  23536. }
  23537. }
  23538. // Sides
  23539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23540. // Result
  23541. var vertexData = new VertexData();
  23542. vertexData.indices = indices;
  23543. vertexData.positions = positions;
  23544. vertexData.normals = normals;
  23545. vertexData.uvs = uvs;
  23546. return vertexData;
  23547. };
  23548. // Cylinder and cone
  23549. VertexData.CreateCylinder = function (options) {
  23550. var height = options.height || 2;
  23551. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23552. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23553. var tessellation = options.tessellation || 24;
  23554. var subdivisions = options.subdivisions || 1;
  23555. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23556. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23557. var faceUV = options.faceUV || new Array(3);
  23558. var faceColors = options.faceColors;
  23559. // default face colors and UV if undefined
  23560. for (var f = 0; f < 3; f++) {
  23561. if (faceColors && faceColors[f] === undefined) {
  23562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23563. }
  23564. if (faceUV && faceUV[f] === undefined) {
  23565. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23566. }
  23567. }
  23568. var indices = [];
  23569. var positions = [];
  23570. var normals = [];
  23571. var uvs = [];
  23572. var colors = [];
  23573. var angle_step = Math.PI * 2 * arc / tessellation;
  23574. var angle;
  23575. var h;
  23576. var radius;
  23577. var tan = (diameterBottom - diameterTop) / 2 / height;
  23578. var ringVertex = BABYLON.Vector3.Zero();
  23579. var ringNormal = BABYLON.Vector3.Zero();
  23580. // positions, normals, uvs
  23581. var i;
  23582. var j;
  23583. for (i = 0; i <= subdivisions; i++) {
  23584. h = i / subdivisions;
  23585. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23586. for (j = 0; j <= tessellation; j++) {
  23587. angle = j * angle_step;
  23588. ringVertex.x = Math.cos(-angle) * radius;
  23589. ringVertex.y = -height / 2 + h * height;
  23590. ringVertex.z = Math.sin(-angle) * radius;
  23591. if (diameterTop === 0 && i === subdivisions) {
  23592. // if no top cap, reuse former normals
  23593. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23594. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23595. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23596. }
  23597. else {
  23598. ringNormal.x = ringVertex.x;
  23599. ringNormal.z = ringVertex.z;
  23600. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23601. ringNormal.normalize();
  23602. }
  23603. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23604. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23605. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23606. if (faceColors) {
  23607. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23608. }
  23609. }
  23610. }
  23611. // indices
  23612. for (i = 0; i < subdivisions; i++) {
  23613. for (j = 0; j < tessellation; j++) {
  23614. var i0 = i * (tessellation + 1) + j;
  23615. var i1 = (i + 1) * (tessellation + 1) + j;
  23616. var i2 = i * (tessellation + 1) + (j + 1);
  23617. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23618. indices.push(i0, i1, i2);
  23619. indices.push(i3, i2, i1);
  23620. }
  23621. }
  23622. // Caps
  23623. var createCylinderCap = function (isTop) {
  23624. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23625. if (radius === 0) {
  23626. return;
  23627. }
  23628. // Cap positions, normals & uvs
  23629. var angle;
  23630. var circleVector;
  23631. var i;
  23632. var u = (isTop) ? faceUV[2] : faceUV[0];
  23633. var c;
  23634. if (faceColors) {
  23635. c = (isTop) ? faceColors[2] : faceColors[0];
  23636. }
  23637. // cap center
  23638. var vbase = positions.length / 3;
  23639. var offset = isTop ? height / 2 : -height / 2;
  23640. var center = new BABYLON.Vector3(0, offset, 0);
  23641. positions.push(center.x, center.y, center.z);
  23642. normals.push(0, isTop ? 1 : -1, 0);
  23643. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23644. if (faceColors) {
  23645. colors.push(c.r, c.g, c.b, c.a);
  23646. }
  23647. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23648. for (i = 0; i <= tessellation; i++) {
  23649. angle = Math.PI * 2 * i * arc / tessellation;
  23650. var cos = Math.cos(-angle);
  23651. var sin = Math.sin(-angle);
  23652. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23653. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23654. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23655. normals.push(0, isTop ? 1 : -1, 0);
  23656. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23657. if (faceColors) {
  23658. colors.push(c.r, c.g, c.b, c.a);
  23659. }
  23660. }
  23661. // Cap indices
  23662. for (i = 0; i < tessellation; i++) {
  23663. if (!isTop) {
  23664. indices.push(vbase);
  23665. indices.push(vbase + (i + 1));
  23666. indices.push(vbase + (i + 2));
  23667. }
  23668. else {
  23669. indices.push(vbase);
  23670. indices.push(vbase + (i + 2));
  23671. indices.push(vbase + (i + 1));
  23672. }
  23673. }
  23674. };
  23675. // add caps to geometry
  23676. createCylinderCap(false);
  23677. createCylinderCap(true);
  23678. // Sides
  23679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23680. var vertexData = new VertexData();
  23681. vertexData.indices = indices;
  23682. vertexData.positions = positions;
  23683. vertexData.normals = normals;
  23684. vertexData.uvs = uvs;
  23685. if (faceColors) {
  23686. vertexData.colors = colors;
  23687. }
  23688. return vertexData;
  23689. };
  23690. VertexData.CreateTorus = function (options) {
  23691. var indices = [];
  23692. var positions = [];
  23693. var normals = [];
  23694. var uvs = [];
  23695. var diameter = options.diameter || 1;
  23696. var thickness = options.thickness || 0.5;
  23697. var tessellation = options.tessellation || 16;
  23698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23699. var stride = tessellation + 1;
  23700. for (var i = 0; i <= tessellation; i++) {
  23701. var u = i / tessellation;
  23702. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23703. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23704. for (var j = 0; j <= tessellation; j++) {
  23705. var v = 1 - j / tessellation;
  23706. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23707. var dx = Math.cos(innerAngle);
  23708. var dy = Math.sin(innerAngle);
  23709. // Create a vertex.
  23710. var normal = new BABYLON.Vector3(dx, dy, 0);
  23711. var position = normal.scale(thickness / 2);
  23712. var textureCoordinate = new BABYLON.Vector2(u, v);
  23713. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23714. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23715. positions.push(position.x, position.y, position.z);
  23716. normals.push(normal.x, normal.y, normal.z);
  23717. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23718. // And create indices for two triangles.
  23719. var nextI = (i + 1) % stride;
  23720. var nextJ = (j + 1) % stride;
  23721. indices.push(i * stride + j);
  23722. indices.push(i * stride + nextJ);
  23723. indices.push(nextI * stride + j);
  23724. indices.push(i * stride + nextJ);
  23725. indices.push(nextI * stride + nextJ);
  23726. indices.push(nextI * stride + j);
  23727. }
  23728. }
  23729. // Sides
  23730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23731. // Result
  23732. var vertexData = new VertexData();
  23733. vertexData.indices = indices;
  23734. vertexData.positions = positions;
  23735. vertexData.normals = normals;
  23736. vertexData.uvs = uvs;
  23737. return vertexData;
  23738. };
  23739. VertexData.CreateLines = function (options) {
  23740. var indices = [];
  23741. var positions = [];
  23742. var points = options.points;
  23743. for (var index = 0; index < points.length; index++) {
  23744. positions.push(points[index].x, points[index].y, points[index].z);
  23745. if (index > 0) {
  23746. indices.push(index - 1);
  23747. indices.push(index);
  23748. }
  23749. }
  23750. // Result
  23751. var vertexData = new VertexData();
  23752. vertexData.indices = indices;
  23753. vertexData.positions = positions;
  23754. return vertexData;
  23755. };
  23756. VertexData.CreateDashedLines = function (options) {
  23757. var dashSize = options.dashSize || 3;
  23758. var gapSize = options.gapSize || 1;
  23759. var dashNb = options.dashNb || 200;
  23760. var points = options.points;
  23761. var positions = new Array();
  23762. var indices = new Array();
  23763. var curvect = BABYLON.Vector3.Zero();
  23764. var lg = 0;
  23765. var nb = 0;
  23766. var shft = 0;
  23767. var dashshft = 0;
  23768. var curshft = 0;
  23769. var idx = 0;
  23770. var i = 0;
  23771. for (i = 0; i < points.length - 1; i++) {
  23772. points[i + 1].subtractToRef(points[i], curvect);
  23773. lg += curvect.length();
  23774. }
  23775. shft = lg / dashNb;
  23776. dashshft = dashSize * shft / (dashSize + gapSize);
  23777. for (i = 0; i < points.length - 1; i++) {
  23778. points[i + 1].subtractToRef(points[i], curvect);
  23779. nb = Math.floor(curvect.length() / shft);
  23780. curvect.normalize();
  23781. for (var j = 0; j < nb; j++) {
  23782. curshft = shft * j;
  23783. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23784. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23785. indices.push(idx, idx + 1);
  23786. idx += 2;
  23787. }
  23788. }
  23789. // Result
  23790. var vertexData = new VertexData();
  23791. vertexData.positions = positions;
  23792. vertexData.indices = indices;
  23793. return vertexData;
  23794. };
  23795. VertexData.CreateGround = function (options) {
  23796. var indices = [];
  23797. var positions = [];
  23798. var normals = [];
  23799. var uvs = [];
  23800. var row, col;
  23801. var width = options.width || 1;
  23802. var height = options.height || 1;
  23803. var subdivisions = options.subdivisions || 1;
  23804. for (row = 0; row <= subdivisions; row++) {
  23805. for (col = 0; col <= subdivisions; col++) {
  23806. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23807. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23808. positions.push(position.x, position.y, position.z);
  23809. normals.push(normal.x, normal.y, normal.z);
  23810. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23811. }
  23812. }
  23813. for (row = 0; row < subdivisions; row++) {
  23814. for (col = 0; col < subdivisions; col++) {
  23815. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23816. indices.push(col + 1 + row * (subdivisions + 1));
  23817. indices.push(col + row * (subdivisions + 1));
  23818. indices.push(col + (row + 1) * (subdivisions + 1));
  23819. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23820. indices.push(col + row * (subdivisions + 1));
  23821. }
  23822. }
  23823. // Result
  23824. var vertexData = new VertexData();
  23825. vertexData.indices = indices;
  23826. vertexData.positions = positions;
  23827. vertexData.normals = normals;
  23828. vertexData.uvs = uvs;
  23829. return vertexData;
  23830. };
  23831. VertexData.CreateTiledGround = function (options) {
  23832. var xmin = options.xmin;
  23833. var zmin = options.zmin;
  23834. var xmax = options.xmax;
  23835. var zmax = options.zmax;
  23836. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23837. var precision = options.precision || { w: 1, h: 1 };
  23838. var indices = [];
  23839. var positions = [];
  23840. var normals = [];
  23841. var uvs = [];
  23842. var row, col, tileRow, tileCol;
  23843. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23844. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23845. precision.w = (precision.w < 1) ? 1 : precision.w;
  23846. precision.h = (precision.h < 1) ? 1 : precision.h;
  23847. var tileSize = {
  23848. 'w': (xmax - xmin) / subdivisions.w,
  23849. 'h': (zmax - zmin) / subdivisions.h
  23850. };
  23851. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23852. // Indices
  23853. var base = positions.length / 3;
  23854. var rowLength = precision.w + 1;
  23855. for (row = 0; row < precision.h; row++) {
  23856. for (col = 0; col < precision.w; col++) {
  23857. var square = [
  23858. base + col + row * rowLength,
  23859. base + (col + 1) + row * rowLength,
  23860. base + (col + 1) + (row + 1) * rowLength,
  23861. base + col + (row + 1) * rowLength
  23862. ];
  23863. indices.push(square[1]);
  23864. indices.push(square[2]);
  23865. indices.push(square[3]);
  23866. indices.push(square[0]);
  23867. indices.push(square[1]);
  23868. indices.push(square[3]);
  23869. }
  23870. }
  23871. // Position, normals and uvs
  23872. var position = BABYLON.Vector3.Zero();
  23873. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23874. for (row = 0; row <= precision.h; row++) {
  23875. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23876. for (col = 0; col <= precision.w; col++) {
  23877. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23878. position.y = 0;
  23879. positions.push(position.x, position.y, position.z);
  23880. normals.push(normal.x, normal.y, normal.z);
  23881. uvs.push(col / precision.w, row / precision.h);
  23882. }
  23883. }
  23884. }
  23885. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23886. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23887. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23888. }
  23889. }
  23890. // Result
  23891. var vertexData = new VertexData();
  23892. vertexData.indices = indices;
  23893. vertexData.positions = positions;
  23894. vertexData.normals = normals;
  23895. vertexData.uvs = uvs;
  23896. return vertexData;
  23897. };
  23898. VertexData.CreateGroundFromHeightMap = function (options) {
  23899. var indices = [];
  23900. var positions = [];
  23901. var normals = [];
  23902. var uvs = [];
  23903. var row, col;
  23904. // Vertices
  23905. for (row = 0; row <= options.subdivisions; row++) {
  23906. for (col = 0; col <= options.subdivisions; col++) {
  23907. 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));
  23908. // Compute height
  23909. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23910. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23911. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23912. var r = options.buffer[pos] / 255.0;
  23913. var g = options.buffer[pos + 1] / 255.0;
  23914. var b = options.buffer[pos + 2] / 255.0;
  23915. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23916. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23917. // Add vertex
  23918. positions.push(position.x, position.y, position.z);
  23919. normals.push(0, 0, 0);
  23920. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23921. }
  23922. }
  23923. // Indices
  23924. for (row = 0; row < options.subdivisions; row++) {
  23925. for (col = 0; col < options.subdivisions; col++) {
  23926. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23927. indices.push(col + 1 + row * (options.subdivisions + 1));
  23928. indices.push(col + row * (options.subdivisions + 1));
  23929. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23930. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23931. indices.push(col + row * (options.subdivisions + 1));
  23932. }
  23933. }
  23934. // Normals
  23935. VertexData.ComputeNormals(positions, indices, normals);
  23936. // Result
  23937. var vertexData = new VertexData();
  23938. vertexData.indices = indices;
  23939. vertexData.positions = positions;
  23940. vertexData.normals = normals;
  23941. vertexData.uvs = uvs;
  23942. return vertexData;
  23943. };
  23944. VertexData.CreatePlane = function (options) {
  23945. var indices = [];
  23946. var positions = [];
  23947. var normals = [];
  23948. var uvs = [];
  23949. var width = options.width || options.size || 1;
  23950. var height = options.height || options.size || 1;
  23951. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23952. // Vertices
  23953. var halfWidth = width / 2.0;
  23954. var halfHeight = height / 2.0;
  23955. positions.push(-halfWidth, -halfHeight, 0);
  23956. normals.push(0, 0, -1.0);
  23957. uvs.push(0.0, 0.0);
  23958. positions.push(halfWidth, -halfHeight, 0);
  23959. normals.push(0, 0, -1.0);
  23960. uvs.push(1.0, 0.0);
  23961. positions.push(halfWidth, halfHeight, 0);
  23962. normals.push(0, 0, -1.0);
  23963. uvs.push(1.0, 1.0);
  23964. positions.push(-halfWidth, halfHeight, 0);
  23965. normals.push(0, 0, -1.0);
  23966. uvs.push(0.0, 1.0);
  23967. // Indices
  23968. indices.push(0);
  23969. indices.push(1);
  23970. indices.push(2);
  23971. indices.push(0);
  23972. indices.push(2);
  23973. indices.push(3);
  23974. // Sides
  23975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23976. // Result
  23977. var vertexData = new VertexData();
  23978. vertexData.indices = indices;
  23979. vertexData.positions = positions;
  23980. vertexData.normals = normals;
  23981. vertexData.uvs = uvs;
  23982. return vertexData;
  23983. };
  23984. VertexData.CreateDisc = function (options) {
  23985. var positions = [];
  23986. var indices = [];
  23987. var normals = [];
  23988. var uvs = [];
  23989. var radius = options.radius || 0.5;
  23990. var tessellation = options.tessellation || 64;
  23991. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23992. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23993. // positions and uvs
  23994. positions.push(0, 0, 0); // disc center first
  23995. uvs.push(0.5, 0.5);
  23996. var theta = Math.PI * 2 * arc;
  23997. var step = theta / tessellation;
  23998. for (var a = 0; a < theta; a += step) {
  23999. var x = Math.cos(a);
  24000. var y = Math.sin(a);
  24001. var u = (x + 1) / 2;
  24002. var v = (1 - y) / 2;
  24003. positions.push(radius * x, radius * y, 0);
  24004. uvs.push(u, v);
  24005. }
  24006. if (arc === 1) {
  24007. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24008. uvs.push(uvs[2], uvs[3]);
  24009. }
  24010. //indices
  24011. var vertexNb = positions.length / 3;
  24012. for (var i = 1; i < vertexNb - 1; i++) {
  24013. indices.push(i + 1, 0, i);
  24014. }
  24015. // result
  24016. VertexData.ComputeNormals(positions, indices, normals);
  24017. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24018. var vertexData = new VertexData();
  24019. vertexData.indices = indices;
  24020. vertexData.positions = positions;
  24021. vertexData.normals = normals;
  24022. vertexData.uvs = uvs;
  24023. return vertexData;
  24024. };
  24025. VertexData.CreateIcoSphere = function (options) {
  24026. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24027. var radius = options.radius || 1;
  24028. var flat = (options.flat === undefined) ? true : options.flat;
  24029. var subdivisions = options.subdivisions || 4;
  24030. var radiusX = options.radiusX || radius;
  24031. var radiusY = options.radiusY || radius;
  24032. var radiusZ = options.radiusZ || radius;
  24033. var t = (1 + Math.sqrt(5)) / 2;
  24034. // 12 vertex x,y,z
  24035. var ico_vertices = [
  24036. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24037. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24038. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24039. ];
  24040. // index of 3 vertex makes a face of icopshere
  24041. var ico_indices = [
  24042. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  24043. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  24044. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  24045. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  24046. ];
  24047. // uv as integer step (not pixels !)
  24048. var ico_vertexuv = [
  24049. 4, 1, 2, 1, 6, 3, 5, 4,
  24050. 4, 3, 3, 2, 7, 4, 3, 0,
  24051. 1, 0, 0, 1, 5, 0, 5, 2 // v8-11
  24052. ];
  24053. // Vertices [0, 1, ...9, A, B] : position on UV plane (7,8,9,10=A have duplicate position)
  24054. // v=5h 9+ 8+ 7+
  24055. // v=4h 9+ 3 6 A+
  24056. // v=3h 9+ 4 2 A+
  24057. // v=2h 9+ 5 B A+
  24058. // v=1h 9 1 0 A+
  24059. // v=0h 8 7 A
  24060. // u=0 1 2 3 4 5 6 7 8 9 *a
  24061. //
  24062. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24063. var ustep = 97 / 1024;
  24064. var vstep = 168 / 1024;
  24065. var uoffset = 50 / 1024;
  24066. var voffset = 51 / 1024;
  24067. var indices = [];
  24068. var positions = [];
  24069. var normals = [];
  24070. var uvs = [];
  24071. var current_indice = 0;
  24072. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24073. var face_vertex_pos = new Array(3);
  24074. var face_vertex_uv = new Array(3);
  24075. for (var v012 = 0; v012 < 3; v012++) {
  24076. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24077. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24078. }
  24079. // create all with normals
  24080. for (var face = 0; face < 20; face++) {
  24081. // 3 vertex per face
  24082. for (var v012 = 0; v012 < 3; v012++) {
  24083. // look up vertex 0,1,2 to its index in 0 to 11
  24084. var v_id = ico_indices[3 * face + v012];
  24085. // vertex have 3D position (x,y,z)
  24086. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * v_id], ico_vertices[3 * v_id + 1], ico_vertices[3 * v_id + 2]);
  24087. // Normalize to get normal, then scale to radius
  24088. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24089. // uv from vertex ID (may need fix due to unwrap on texture plan, unalias needed)
  24090. // vertex may get to different UV according to belonging face (see fix below)
  24091. var fix = 0;
  24092. // Vertice 9 UV to be fixed
  24093. if (face === 5 && v012 === 2) {
  24094. fix = 1;
  24095. }
  24096. if (face === 15 && v012 === 1) {
  24097. fix = 2;
  24098. }
  24099. if (face === 10 && v012 === 1) {
  24100. fix = 3;
  24101. }
  24102. if (face === 14 && v012 === 2) {
  24103. fix = 4;
  24104. }
  24105. // vertice 10 UV to be fixed
  24106. if (face === 4 && v012 === 1) {
  24107. fix = 1;
  24108. }
  24109. if (face === 7 && v012 === 1) {
  24110. fix = 2;
  24111. }
  24112. if (face === 17 && v012 === 2) {
  24113. fix = 3;
  24114. }
  24115. if (face === 8 && v012 === 0) {
  24116. fix = 4;
  24117. }
  24118. // vertice 7 UV to be fixed
  24119. if (face === 8 && v012 === 1) {
  24120. fix = 5;
  24121. }
  24122. if (face === 18 && v012 === 0) {
  24123. fix = 5;
  24124. }
  24125. // vertice 8 UV to be fixed
  24126. if (face === 13 && v012 === 2) {
  24127. fix = 5;
  24128. }
  24129. if (face === 14 && v012 === 1) {
  24130. fix = 5;
  24131. }
  24132. if (face === 18 && v012 === 2) {
  24133. fix = 5;
  24134. }
  24135. //
  24136. face_vertex_uv[v012].copyFromFloats((ico_vertexuv[2 * v_id] + fix) * ustep + uoffset, (ico_vertexuv[2 * v_id + 1] + fix) * vstep + voffset);
  24137. }
  24138. // Subdivide the face (interpolate pos, norm, uv)
  24139. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24140. // - norm is linear interpolation of vertex corner normal
  24141. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24142. // - uv is linear interpolation
  24143. //
  24144. // Topology is as below for sub-divide by 2
  24145. // vertex shown as v0,v1,v2
  24146. // interp index is i1 to progress in range [v0,v1[
  24147. // interp index is i2 to progress in range [v0,v2[
  24148. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24149. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24150. //
  24151. //
  24152. // i2 v2
  24153. // ^ ^
  24154. // / / \
  24155. // / / \
  24156. // / / \
  24157. // / / (0,1) \
  24158. // / #---------\
  24159. // / / \ (0,0)'/ \
  24160. // / / \ / \
  24161. // / / \ / \
  24162. // / / (0,0) \ / (1,0) \
  24163. // / #---------#---------\
  24164. // v0 v1
  24165. //
  24166. // --------------------> i1
  24167. //
  24168. // interp of (i1,i2):
  24169. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24170. // along i1 : lerp(x0,x1, i1/(S-i2))
  24171. //
  24172. // centroid of triangle is needed to get help normal computation
  24173. // (c1,c2) are used for centroid location
  24174. var interp_vertex = function (i1, i2, c1, c2) {
  24175. // vertex is interpolated from
  24176. // - face_vertex_pos[0..2]
  24177. // - face_vertex_uv[0..2]
  24178. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24179. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24180. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24181. pos_interp.normalize();
  24182. pos_interp.x *= radiusX;
  24183. pos_interp.y *= radiusY;
  24184. pos_interp.z *= radiusZ;
  24185. var vertex_normal;
  24186. if (flat) {
  24187. // in flat mode, recalculate normal as face centroid normal
  24188. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24189. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24190. var centroid_interp = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24191. vertex_normal = BABYLON.Vector3.Normalize(centroid_interp);
  24192. }
  24193. else {
  24194. // in smooth mode, recalculate normal from each single vertex position
  24195. vertex_normal = BABYLON.Vector3.Normalize(pos_interp);
  24196. }
  24197. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24198. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24199. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24200. positions.push(pos_interp.x, pos_interp.y, pos_interp.z);
  24201. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24202. uvs.push(uv_interp.x, uv_interp.y);
  24203. // push each vertex has member of a face
  24204. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24205. indices.push(current_indice);
  24206. current_indice++;
  24207. };
  24208. for (var i2 = 0; i2 < subdivisions; i2++) {
  24209. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24210. // face : (i1,i2) for /\ :
  24211. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24212. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24213. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24214. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24215. if (i1 + i2 + 1 < subdivisions) {
  24216. // face : (i1,i2)' for \/ :
  24217. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24218. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24219. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24220. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24221. }
  24222. }
  24223. }
  24224. }
  24225. // Sides
  24226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24227. // Result
  24228. var vertexData = new VertexData();
  24229. vertexData.indices = indices;
  24230. vertexData.positions = positions;
  24231. vertexData.normals = normals;
  24232. vertexData.uvs = uvs;
  24233. return vertexData;
  24234. };
  24235. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24236. VertexData.CreatePolyhedron = function (options) {
  24237. // provided polyhedron types :
  24238. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24239. // 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)
  24240. var polyhedra = [];
  24241. 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]] };
  24242. 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]] };
  24243. polyhedra[2] = {
  24244. 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]],
  24245. 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]]
  24246. };
  24247. polyhedra[3] = {
  24248. 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]],
  24249. 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]]
  24250. };
  24251. polyhedra[4] = {
  24252. 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]],
  24253. 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]]
  24254. };
  24255. 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]] };
  24256. 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]] };
  24257. 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]] };
  24258. 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]] };
  24259. 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]] };
  24260. 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]] };
  24261. 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]] };
  24262. 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]] };
  24263. 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]] };
  24264. polyhedra[14] = {
  24265. 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]],
  24266. 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]]
  24267. };
  24268. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24269. var size = options.size;
  24270. var sizeX = options.sizeX || size || 1;
  24271. var sizeY = options.sizeY || size || 1;
  24272. var sizeZ = options.sizeZ || size || 1;
  24273. var data = options.custom || polyhedra[type];
  24274. var nbfaces = data.face.length;
  24275. var faceUV = options.faceUV || new Array(nbfaces);
  24276. var faceColors = options.faceColors;
  24277. var flat = (options.flat === undefined) ? true : options.flat;
  24278. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24279. var positions = [];
  24280. var indices = [];
  24281. var normals = [];
  24282. var uvs = [];
  24283. var colors = [];
  24284. var index = 0;
  24285. var faceIdx = 0; // face cursor in the array "indexes"
  24286. var indexes = [];
  24287. var i = 0;
  24288. var f = 0;
  24289. var u, v, ang, x, y, tmp;
  24290. // default face colors and UV if undefined
  24291. if (flat) {
  24292. for (f = 0; f < nbfaces; f++) {
  24293. if (faceColors && faceColors[f] === undefined) {
  24294. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24295. }
  24296. if (faceUV && faceUV[f] === undefined) {
  24297. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24298. }
  24299. }
  24300. }
  24301. if (!flat) {
  24302. for (i = 0; i < data.vertex.length; i++) {
  24303. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24304. uvs.push(0, 0);
  24305. }
  24306. for (f = 0; f < nbfaces; f++) {
  24307. for (i = 0; i < data.face[f].length - 2; i++) {
  24308. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24309. }
  24310. }
  24311. }
  24312. else {
  24313. for (f = 0; f < nbfaces; f++) {
  24314. var fl = data.face[f].length; // number of vertices of the current face
  24315. ang = 2 * Math.PI / fl;
  24316. x = 0.5 * Math.tan(ang / 2);
  24317. y = 0.5;
  24318. // positions, uvs, colors
  24319. for (i = 0; i < fl; i++) {
  24320. // positions
  24321. 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);
  24322. indexes.push(index);
  24323. index++;
  24324. // uvs
  24325. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24326. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24327. uvs.push(u, v);
  24328. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24329. y = x * Math.sin(ang) + y * Math.cos(ang);
  24330. x = tmp;
  24331. // colors
  24332. if (faceColors) {
  24333. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24334. }
  24335. }
  24336. // indices from indexes
  24337. for (i = 0; i < fl - 2; i++) {
  24338. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24339. }
  24340. faceIdx += fl;
  24341. }
  24342. }
  24343. VertexData.ComputeNormals(positions, indices, normals);
  24344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24345. var vertexData = new VertexData();
  24346. vertexData.positions = positions;
  24347. vertexData.indices = indices;
  24348. vertexData.normals = normals;
  24349. vertexData.uvs = uvs;
  24350. if (faceColors && flat) {
  24351. vertexData.colors = colors;
  24352. }
  24353. return vertexData;
  24354. };
  24355. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24356. VertexData.CreateTorusKnot = function (options) {
  24357. var indices = [];
  24358. var positions = [];
  24359. var normals = [];
  24360. var uvs = [];
  24361. var radius = options.radius || 2;
  24362. var tube = options.tube || 0.5;
  24363. var radialSegments = options.radialSegments || 32;
  24364. var tubularSegments = options.tubularSegments || 32;
  24365. var p = options.p || 2;
  24366. var q = options.q || 3;
  24367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24368. // Helper
  24369. var getPos = function (angle) {
  24370. var cu = Math.cos(angle);
  24371. var su = Math.sin(angle);
  24372. var quOverP = q / p * angle;
  24373. var cs = Math.cos(quOverP);
  24374. var tx = radius * (2 + cs) * 0.5 * cu;
  24375. var ty = radius * (2 + cs) * su * 0.5;
  24376. var tz = radius * Math.sin(quOverP) * 0.5;
  24377. return new BABYLON.Vector3(tx, ty, tz);
  24378. };
  24379. // Vertices
  24380. var i;
  24381. var j;
  24382. for (i = 0; i <= radialSegments; i++) {
  24383. var modI = i % radialSegments;
  24384. var u = modI / radialSegments * 2 * p * Math.PI;
  24385. var p1 = getPos(u);
  24386. var p2 = getPos(u + 0.01);
  24387. var tang = p2.subtract(p1);
  24388. var n = p2.add(p1);
  24389. var bitan = BABYLON.Vector3.Cross(tang, n);
  24390. n = BABYLON.Vector3.Cross(bitan, tang);
  24391. bitan.normalize();
  24392. n.normalize();
  24393. for (j = 0; j < tubularSegments; j++) {
  24394. var modJ = j % tubularSegments;
  24395. var v = modJ / tubularSegments * 2 * Math.PI;
  24396. var cx = -tube * Math.cos(v);
  24397. var cy = tube * Math.sin(v);
  24398. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24399. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24400. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24401. uvs.push(i / radialSegments);
  24402. uvs.push(j / tubularSegments);
  24403. }
  24404. }
  24405. for (i = 0; i < radialSegments; i++) {
  24406. for (j = 0; j < tubularSegments; j++) {
  24407. var jNext = (j + 1) % tubularSegments;
  24408. var a = i * tubularSegments + j;
  24409. var b = (i + 1) * tubularSegments + j;
  24410. var c = (i + 1) * tubularSegments + jNext;
  24411. var d = i * tubularSegments + jNext;
  24412. indices.push(d);
  24413. indices.push(b);
  24414. indices.push(a);
  24415. indices.push(d);
  24416. indices.push(c);
  24417. indices.push(b);
  24418. }
  24419. }
  24420. // Normals
  24421. VertexData.ComputeNormals(positions, indices, normals);
  24422. // Sides
  24423. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24424. // Result
  24425. var vertexData = new VertexData();
  24426. vertexData.indices = indices;
  24427. vertexData.positions = positions;
  24428. vertexData.normals = normals;
  24429. vertexData.uvs = uvs;
  24430. return vertexData;
  24431. };
  24432. // Tools
  24433. /**
  24434. * @param {any} - positions (number[] or Float32Array)
  24435. * @param {any} - indices (number[] or Uint16Array)
  24436. * @param {any} - normals (number[] or Float32Array)
  24437. */
  24438. VertexData.ComputeNormals = function (positions, indices, normals) {
  24439. var index = 0;
  24440. // temp Vector3
  24441. var p1p2 = BABYLON.Vector3.Zero();
  24442. var p3p2 = BABYLON.Vector3.Zero();
  24443. var faceNormal = BABYLON.Vector3.Zero();
  24444. var vertexNormali1 = BABYLON.Vector3.Zero();
  24445. for (index = 0; index < positions.length; index++) {
  24446. normals[index] = 0.0;
  24447. }
  24448. // indice triplet = 1 face
  24449. var nbFaces = indices.length / 3;
  24450. for (index = 0; index < nbFaces; index++) {
  24451. var i1 = indices[index * 3];
  24452. var i2 = indices[index * 3 + 1];
  24453. var i3 = indices[index * 3 + 2];
  24454. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24455. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24456. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24457. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24458. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24459. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24460. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24461. faceNormal.normalize();
  24462. normals[i1 * 3] += faceNormal.x;
  24463. normals[i1 * 3 + 1] += faceNormal.y;
  24464. normals[i1 * 3 + 2] += faceNormal.z;
  24465. normals[i2 * 3] += faceNormal.x;
  24466. normals[i2 * 3 + 1] += faceNormal.y;
  24467. normals[i2 * 3 + 2] += faceNormal.z;
  24468. normals[i3 * 3] += faceNormal.x;
  24469. normals[i3 * 3 + 1] += faceNormal.y;
  24470. normals[i3 * 3 + 2] += faceNormal.z;
  24471. }
  24472. // last normalization
  24473. for (index = 0; index < normals.length / 3; index++) {
  24474. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24475. vertexNormali1.normalize();
  24476. normals[index * 3] = vertexNormali1.x;
  24477. normals[index * 3 + 1] = vertexNormali1.y;
  24478. normals[index * 3 + 2] = vertexNormali1.z;
  24479. }
  24480. };
  24481. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24482. var li = indices.length;
  24483. var ln = normals.length;
  24484. var i;
  24485. var n;
  24486. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24487. switch (sideOrientation) {
  24488. case BABYLON.Mesh.FRONTSIDE:
  24489. // nothing changed
  24490. break;
  24491. case BABYLON.Mesh.BACKSIDE:
  24492. var tmp;
  24493. // indices
  24494. for (i = 0; i < li; i += 3) {
  24495. tmp = indices[i];
  24496. indices[i] = indices[i + 2];
  24497. indices[i + 2] = tmp;
  24498. }
  24499. // normals
  24500. for (n = 0; n < ln; n++) {
  24501. normals[n] = -normals[n];
  24502. }
  24503. break;
  24504. case BABYLON.Mesh.DOUBLESIDE:
  24505. // positions
  24506. var lp = positions.length;
  24507. var l = lp / 3;
  24508. for (var p = 0; p < lp; p++) {
  24509. positions[lp + p] = positions[p];
  24510. }
  24511. // indices
  24512. for (i = 0; i < li; i += 3) {
  24513. indices[i + li] = indices[i + 2] + l;
  24514. indices[i + 1 + li] = indices[i + 1] + l;
  24515. indices[i + 2 + li] = indices[i] + l;
  24516. }
  24517. // normals
  24518. for (n = 0; n < ln; n++) {
  24519. normals[ln + n] = -normals[n];
  24520. }
  24521. // uvs
  24522. var lu = uvs.length;
  24523. for (var u = 0; u < lu; u++) {
  24524. uvs[u + lu] = uvs[u];
  24525. }
  24526. break;
  24527. }
  24528. };
  24529. return VertexData;
  24530. })();
  24531. BABYLON.VertexData = VertexData;
  24532. })(BABYLON || (BABYLON = {}));
  24533. var BABYLON;
  24534. (function (BABYLON) {
  24535. var Tags = (function () {
  24536. function Tags() {
  24537. }
  24538. Tags.EnableFor = function (obj) {
  24539. obj._tags = obj._tags || {};
  24540. obj.hasTags = function () {
  24541. return Tags.HasTags(obj);
  24542. };
  24543. obj.addTags = function (tagsString) {
  24544. return Tags.AddTagsTo(obj, tagsString);
  24545. };
  24546. obj.removeTags = function (tagsString) {
  24547. return Tags.RemoveTagsFrom(obj, tagsString);
  24548. };
  24549. obj.matchesTagsQuery = function (tagsQuery) {
  24550. return Tags.MatchesQuery(obj, tagsQuery);
  24551. };
  24552. };
  24553. Tags.DisableFor = function (obj) {
  24554. delete obj._tags;
  24555. delete obj.hasTags;
  24556. delete obj.addTags;
  24557. delete obj.removeTags;
  24558. delete obj.matchesTagsQuery;
  24559. };
  24560. Tags.HasTags = function (obj) {
  24561. if (!obj._tags) {
  24562. return false;
  24563. }
  24564. return !BABYLON.Tools.IsEmpty(obj._tags);
  24565. };
  24566. Tags.GetTags = function (obj) {
  24567. if (!obj._tags) {
  24568. return null;
  24569. }
  24570. return obj._tags;
  24571. };
  24572. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24573. // a tag cannot start with '||', '&&', and '!'
  24574. // it cannot contain whitespaces
  24575. Tags.AddTagsTo = function (obj, tagsString) {
  24576. if (!tagsString) {
  24577. return;
  24578. }
  24579. if (typeof tagsString !== "string") {
  24580. return;
  24581. }
  24582. var tags = tagsString.split(" ");
  24583. for (var t in tags) {
  24584. Tags._AddTagTo(obj, tags[t]);
  24585. }
  24586. };
  24587. Tags._AddTagTo = function (obj, tag) {
  24588. tag = tag.trim();
  24589. if (tag === "" || tag === "true" || tag === "false") {
  24590. return;
  24591. }
  24592. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24593. return;
  24594. }
  24595. Tags.EnableFor(obj);
  24596. obj._tags[tag] = true;
  24597. };
  24598. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24599. if (!Tags.HasTags(obj)) {
  24600. return;
  24601. }
  24602. var tags = tagsString.split(" ");
  24603. for (var t in tags) {
  24604. Tags._RemoveTagFrom(obj, tags[t]);
  24605. }
  24606. };
  24607. Tags._RemoveTagFrom = function (obj, tag) {
  24608. delete obj._tags[tag];
  24609. };
  24610. Tags.MatchesQuery = function (obj, tagsQuery) {
  24611. if (tagsQuery === undefined) {
  24612. return true;
  24613. }
  24614. if (tagsQuery === "") {
  24615. return Tags.HasTags(obj);
  24616. }
  24617. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24618. };
  24619. return Tags;
  24620. })();
  24621. BABYLON.Tags = Tags;
  24622. })(BABYLON || (BABYLON = {}));
  24623. var BABYLON;
  24624. (function (BABYLON) {
  24625. var Internals;
  24626. (function (Internals) {
  24627. var AndOrNotEvaluator = (function () {
  24628. function AndOrNotEvaluator() {
  24629. }
  24630. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24631. if (!query.match(/\([^\(\)]*\)/g)) {
  24632. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24633. }
  24634. else {
  24635. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24636. // remove parenthesis
  24637. r = r.slice(1, r.length - 1);
  24638. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24639. });
  24640. }
  24641. if (query === "true") {
  24642. return true;
  24643. }
  24644. if (query === "false") {
  24645. return false;
  24646. }
  24647. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24648. };
  24649. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24650. evaluateCallback = evaluateCallback || (function (r) {
  24651. return r === "true" ? true : false;
  24652. });
  24653. var result;
  24654. var or = parenthesisContent.split("||");
  24655. for (var i in or) {
  24656. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24657. var and = ori.split("&&");
  24658. if (and.length > 1) {
  24659. for (var j = 0; j < and.length; ++j) {
  24660. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24661. if (andj !== "true" && andj !== "false") {
  24662. if (andj[0] === "!") {
  24663. result = !evaluateCallback(andj.substring(1));
  24664. }
  24665. else {
  24666. result = evaluateCallback(andj);
  24667. }
  24668. }
  24669. else {
  24670. result = andj === "true" ? true : false;
  24671. }
  24672. if (!result) {
  24673. ori = "false";
  24674. break;
  24675. }
  24676. }
  24677. }
  24678. if (result || ori === "true") {
  24679. result = true;
  24680. break;
  24681. }
  24682. // result equals false (or undefined)
  24683. if (ori !== "true" && ori !== "false") {
  24684. if (ori[0] === "!") {
  24685. result = !evaluateCallback(ori.substring(1));
  24686. }
  24687. else {
  24688. result = evaluateCallback(ori);
  24689. }
  24690. }
  24691. else {
  24692. result = ori === "true" ? true : false;
  24693. }
  24694. }
  24695. // the whole parenthesis scope is replaced by 'true' or 'false'
  24696. return result ? "true" : "false";
  24697. };
  24698. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24699. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24700. // remove whitespaces
  24701. r = r.replace(/[\s]/g, function () { return ""; });
  24702. return r.length % 2 ? "!" : "";
  24703. });
  24704. booleanString = booleanString.trim();
  24705. if (booleanString === "!true") {
  24706. booleanString = "false";
  24707. }
  24708. else if (booleanString === "!false") {
  24709. booleanString = "true";
  24710. }
  24711. return booleanString;
  24712. };
  24713. return AndOrNotEvaluator;
  24714. })();
  24715. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24716. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24717. })(BABYLON || (BABYLON = {}));
  24718. var BABYLON;
  24719. (function (BABYLON) {
  24720. var PostProcessRenderPass = (function () {
  24721. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24722. this._enabled = true;
  24723. this._refCount = 0;
  24724. this._name = name;
  24725. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24726. this.setRenderList(renderList);
  24727. this._renderTexture.onBeforeRender = beforeRender;
  24728. this._renderTexture.onAfterRender = afterRender;
  24729. this._scene = scene;
  24730. this._renderList = renderList;
  24731. }
  24732. // private
  24733. PostProcessRenderPass.prototype._incRefCount = function () {
  24734. if (this._refCount === 0) {
  24735. this._scene.customRenderTargets.push(this._renderTexture);
  24736. }
  24737. return ++this._refCount;
  24738. };
  24739. PostProcessRenderPass.prototype._decRefCount = function () {
  24740. this._refCount--;
  24741. if (this._refCount <= 0) {
  24742. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24743. }
  24744. return this._refCount;
  24745. };
  24746. PostProcessRenderPass.prototype._update = function () {
  24747. this.setRenderList(this._renderList);
  24748. };
  24749. // public
  24750. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24751. this._renderTexture.renderList = renderList;
  24752. };
  24753. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24754. return this._renderTexture;
  24755. };
  24756. return PostProcessRenderPass;
  24757. })();
  24758. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24759. })(BABYLON || (BABYLON = {}));
  24760. var BABYLON;
  24761. (function (BABYLON) {
  24762. var PostProcessRenderEffect = (function () {
  24763. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24764. this._engine = engine;
  24765. this._name = name;
  24766. this._singleInstance = singleInstance || true;
  24767. this._getPostProcess = getPostProcess;
  24768. this._cameras = [];
  24769. this._indicesForCamera = [];
  24770. this._postProcesses = {};
  24771. this._renderPasses = {};
  24772. this._renderEffectAsPasses = {};
  24773. }
  24774. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24775. get: function () {
  24776. for (var index in this._postProcesses) {
  24777. if (!this._postProcesses[index].isSupported) {
  24778. return false;
  24779. }
  24780. }
  24781. return true;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. PostProcessRenderEffect.prototype._update = function () {
  24787. for (var renderPassName in this._renderPasses) {
  24788. this._renderPasses[renderPassName]._update();
  24789. }
  24790. };
  24791. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24792. this._renderPasses[renderPass._name] = renderPass;
  24793. this._linkParameters();
  24794. };
  24795. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24796. delete this._renderPasses[renderPass._name];
  24797. this._linkParameters();
  24798. };
  24799. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24800. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24801. this._linkParameters();
  24802. };
  24803. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24804. for (var renderPassName in this._renderPasses) {
  24805. if (renderPassName === passName) {
  24806. return this._renderPasses[passName];
  24807. }
  24808. }
  24809. };
  24810. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24811. this._renderPasses = {};
  24812. this._linkParameters();
  24813. };
  24814. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24815. var cameraKey;
  24816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24817. for (var i = 0; i < _cam.length; i++) {
  24818. var camera = _cam[i];
  24819. var cameraName = camera.name;
  24820. if (this._singleInstance) {
  24821. cameraKey = 0;
  24822. }
  24823. else {
  24824. cameraKey = cameraName;
  24825. }
  24826. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24827. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24828. if (!this._indicesForCamera[cameraName]) {
  24829. this._indicesForCamera[cameraName] = [];
  24830. }
  24831. this._indicesForCamera[cameraName].push(index);
  24832. if (this._cameras.indexOf(camera) === -1) {
  24833. this._cameras[cameraName] = camera;
  24834. }
  24835. for (var passName in this._renderPasses) {
  24836. this._renderPasses[passName]._incRefCount();
  24837. }
  24838. }
  24839. this._linkParameters();
  24840. };
  24841. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24842. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24843. for (var i = 0; i < _cam.length; i++) {
  24844. var camera = _cam[i];
  24845. var cameraName = camera.name;
  24846. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24847. var index = this._cameras.indexOf(cameraName);
  24848. this._indicesForCamera.splice(index, 1);
  24849. this._cameras.splice(index, 1);
  24850. for (var passName in this._renderPasses) {
  24851. this._renderPasses[passName]._decRefCount();
  24852. }
  24853. }
  24854. };
  24855. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24856. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24857. for (var i = 0; i < _cam.length; i++) {
  24858. var camera = _cam[i];
  24859. var cameraName = camera.name;
  24860. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24861. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24862. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24863. }
  24864. }
  24865. for (var passName in this._renderPasses) {
  24866. this._renderPasses[passName]._incRefCount();
  24867. }
  24868. }
  24869. };
  24870. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24871. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24872. for (var i = 0; i < _cam.length; i++) {
  24873. var camera = _cam[i];
  24874. var cameraName = camera.Name;
  24875. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24876. for (var passName in this._renderPasses) {
  24877. this._renderPasses[passName]._decRefCount();
  24878. }
  24879. }
  24880. };
  24881. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24882. if (this._singleInstance) {
  24883. return this._postProcesses[0];
  24884. }
  24885. else {
  24886. return this._postProcesses[camera.name];
  24887. }
  24888. };
  24889. PostProcessRenderEffect.prototype._linkParameters = function () {
  24890. var _this = this;
  24891. for (var index in this._postProcesses) {
  24892. if (this.applyParameters) {
  24893. this.applyParameters(this._postProcesses[index]);
  24894. }
  24895. this._postProcesses[index].onBeforeRender = function (effect) {
  24896. _this._linkTextures(effect);
  24897. };
  24898. }
  24899. };
  24900. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24901. for (var renderPassName in this._renderPasses) {
  24902. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24903. }
  24904. for (var renderEffectName in this._renderEffectAsPasses) {
  24905. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24906. }
  24907. };
  24908. return PostProcessRenderEffect;
  24909. })();
  24910. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24911. })(BABYLON || (BABYLON = {}));
  24912. var BABYLON;
  24913. (function (BABYLON) {
  24914. var PostProcessRenderPipeline = (function () {
  24915. function PostProcessRenderPipeline(engine, name) {
  24916. this._engine = engine;
  24917. this._name = name;
  24918. this._renderEffects = {};
  24919. this._renderEffectsForIsolatedPass = {};
  24920. this._cameras = [];
  24921. }
  24922. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24923. get: function () {
  24924. for (var renderEffectName in this._renderEffects) {
  24925. if (!this._renderEffects[renderEffectName].isSupported) {
  24926. return false;
  24927. }
  24928. }
  24929. return true;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24935. this._renderEffects[renderEffect._name] = renderEffect;
  24936. };
  24937. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24938. var renderEffects = this._renderEffects[renderEffectName];
  24939. if (!renderEffects) {
  24940. return;
  24941. }
  24942. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24943. };
  24944. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24945. var renderEffects = this._renderEffects[renderEffectName];
  24946. if (!renderEffects) {
  24947. return;
  24948. }
  24949. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24950. };
  24951. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24952. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24953. var indicesToDelete = [];
  24954. var i;
  24955. for (i = 0; i < _cam.length; i++) {
  24956. var camera = _cam[i];
  24957. var cameraName = camera.name;
  24958. if (this._cameras.indexOf(camera) === -1) {
  24959. this._cameras[cameraName] = camera;
  24960. }
  24961. else if (unique) {
  24962. indicesToDelete.push(i);
  24963. }
  24964. }
  24965. for (i = 0; i < indicesToDelete.length; i++) {
  24966. cameras.splice(indicesToDelete[i], 1);
  24967. }
  24968. for (var renderEffectName in this._renderEffects) {
  24969. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24970. }
  24971. };
  24972. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24973. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24974. for (var renderEffectName in this._renderEffects) {
  24975. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24976. }
  24977. for (var i = 0; i < _cam.length; i++) {
  24978. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24979. }
  24980. };
  24981. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24982. var _this = this;
  24983. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24984. var pass = null;
  24985. var renderEffectName;
  24986. for (renderEffectName in this._renderEffects) {
  24987. pass = this._renderEffects[renderEffectName].getPass(passName);
  24988. if (pass != null) {
  24989. break;
  24990. }
  24991. }
  24992. if (pass === null) {
  24993. return;
  24994. }
  24995. for (renderEffectName in this._renderEffects) {
  24996. this._renderEffects[renderEffectName]._disable(_cam);
  24997. }
  24998. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24999. for (var i = 0; i < _cam.length; i++) {
  25000. var camera = _cam[i];
  25001. var cameraName = camera.name;
  25002. 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); });
  25003. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25004. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25005. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25006. }
  25007. };
  25008. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25009. var _this = this;
  25010. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25011. for (var i = 0; i < _cam.length; i++) {
  25012. var camera = _cam[i];
  25013. var cameraName = camera.name;
  25014. 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); });
  25015. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25016. }
  25017. for (var renderEffectName in this._renderEffects) {
  25018. this._renderEffects[renderEffectName]._enable(_cam);
  25019. }
  25020. };
  25021. PostProcessRenderPipeline.prototype._update = function () {
  25022. for (var renderEffectName in this._renderEffects) {
  25023. this._renderEffects[renderEffectName]._update();
  25024. }
  25025. for (var i = 0; i < this._cameras.length; i++) {
  25026. var cameraName = this._cameras[i].name;
  25027. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25028. this._renderEffectsForIsolatedPass[cameraName]._update();
  25029. }
  25030. }
  25031. };
  25032. PostProcessRenderPipeline.prototype.dispose = function () {
  25033. // Must be implemented by children
  25034. };
  25035. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25036. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25037. return PostProcessRenderPipeline;
  25038. })();
  25039. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25040. })(BABYLON || (BABYLON = {}));
  25041. var BABYLON;
  25042. (function (BABYLON) {
  25043. var PostProcessRenderPipelineManager = (function () {
  25044. function PostProcessRenderPipelineManager() {
  25045. this._renderPipelines = {};
  25046. }
  25047. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25048. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25049. };
  25050. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25051. var renderPipeline = this._renderPipelines[renderPipelineName];
  25052. if (!renderPipeline) {
  25053. return;
  25054. }
  25055. renderPipeline._attachCameras(cameras, unique);
  25056. };
  25057. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25058. var renderPipeline = this._renderPipelines[renderPipelineName];
  25059. if (!renderPipeline) {
  25060. return;
  25061. }
  25062. renderPipeline._detachCameras(cameras);
  25063. };
  25064. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25065. var renderPipeline = this._renderPipelines[renderPipelineName];
  25066. if (!renderPipeline) {
  25067. return;
  25068. }
  25069. renderPipeline._enableEffect(renderEffectName, cameras);
  25070. };
  25071. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25072. var renderPipeline = this._renderPipelines[renderPipelineName];
  25073. if (!renderPipeline) {
  25074. return;
  25075. }
  25076. renderPipeline._disableEffect(renderEffectName, cameras);
  25077. };
  25078. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25079. var renderPipeline = this._renderPipelines[renderPipelineName];
  25080. if (!renderPipeline) {
  25081. return;
  25082. }
  25083. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25084. };
  25085. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25086. var renderPipeline = this._renderPipelines[renderPipelineName];
  25087. if (!renderPipeline) {
  25088. return;
  25089. }
  25090. renderPipeline._disableDisplayOnlyPass(cameras);
  25091. };
  25092. PostProcessRenderPipelineManager.prototype.update = function () {
  25093. for (var renderPipelineName in this._renderPipelines) {
  25094. var pipeline = this._renderPipelines[renderPipelineName];
  25095. if (!pipeline.isSupported) {
  25096. pipeline.dispose();
  25097. delete this._renderPipelines[renderPipelineName];
  25098. }
  25099. else {
  25100. pipeline._update();
  25101. }
  25102. }
  25103. };
  25104. return PostProcessRenderPipelineManager;
  25105. })();
  25106. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25107. })(BABYLON || (BABYLON = {}));
  25108. var BABYLON;
  25109. (function (BABYLON) {
  25110. var BoundingBoxRenderer = (function () {
  25111. function BoundingBoxRenderer(scene) {
  25112. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25113. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25114. this.showBackLines = true;
  25115. this.renderList = new BABYLON.SmartArray(32);
  25116. this._scene = scene;
  25117. }
  25118. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25119. if (this._colorShader) {
  25120. return;
  25121. }
  25122. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25123. attributes: ["position"],
  25124. uniforms: ["worldViewProjection", "color"]
  25125. });
  25126. var engine = this._scene.getEngine();
  25127. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25128. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25129. 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]);
  25130. };
  25131. BoundingBoxRenderer.prototype.reset = function () {
  25132. this.renderList.reset();
  25133. };
  25134. BoundingBoxRenderer.prototype.render = function () {
  25135. if (this.renderList.length === 0) {
  25136. return;
  25137. }
  25138. this._prepareRessources();
  25139. if (!this._colorShader.isReady()) {
  25140. return;
  25141. }
  25142. var engine = this._scene.getEngine();
  25143. engine.setDepthWrite(false);
  25144. this._colorShader._preBind();
  25145. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25146. var boundingBox = this.renderList.data[boundingBoxIndex];
  25147. var min = boundingBox.minimum;
  25148. var max = boundingBox.maximum;
  25149. var diff = max.subtract(min);
  25150. var median = min.add(diff.scale(0.5));
  25151. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25152. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25153. .multiply(boundingBox.getWorldMatrix());
  25154. // VBOs
  25155. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25156. if (this.showBackLines) {
  25157. // Back
  25158. engine.setDepthFunctionToGreaterOrEqual();
  25159. this._scene.resetCachedMaterial();
  25160. this._colorShader.setColor4("color", this.backColor.toColor4());
  25161. this._colorShader.bind(worldMatrix);
  25162. // Draw order
  25163. engine.draw(false, 0, 24);
  25164. }
  25165. // Front
  25166. engine.setDepthFunctionToLess();
  25167. this._scene.resetCachedMaterial();
  25168. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25169. this._colorShader.bind(worldMatrix);
  25170. // Draw order
  25171. engine.draw(false, 0, 24);
  25172. }
  25173. this._colorShader.unbind();
  25174. engine.setDepthFunctionToLessOrEqual();
  25175. engine.setDepthWrite(true);
  25176. };
  25177. BoundingBoxRenderer.prototype.dispose = function () {
  25178. if (!this._colorShader) {
  25179. return;
  25180. }
  25181. this._colorShader.dispose();
  25182. this._vb.dispose();
  25183. this._scene.getEngine()._releaseBuffer(this._ib);
  25184. };
  25185. return BoundingBoxRenderer;
  25186. })();
  25187. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25188. })(BABYLON || (BABYLON = {}));
  25189. var BABYLON;
  25190. (function (BABYLON) {
  25191. var Condition = (function () {
  25192. function Condition(actionManager) {
  25193. this._actionManager = actionManager;
  25194. }
  25195. Condition.prototype.isValid = function () {
  25196. return true;
  25197. };
  25198. Condition.prototype._getProperty = function (propertyPath) {
  25199. return this._actionManager._getProperty(propertyPath);
  25200. };
  25201. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25202. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25203. };
  25204. return Condition;
  25205. })();
  25206. BABYLON.Condition = Condition;
  25207. var ValueCondition = (function (_super) {
  25208. __extends(ValueCondition, _super);
  25209. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25210. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25211. _super.call(this, actionManager);
  25212. this.propertyPath = propertyPath;
  25213. this.value = value;
  25214. this.operator = operator;
  25215. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25216. this._property = this._getProperty(this.propertyPath);
  25217. }
  25218. Object.defineProperty(ValueCondition, "IsEqual", {
  25219. get: function () {
  25220. return ValueCondition._IsEqual;
  25221. },
  25222. enumerable: true,
  25223. configurable: true
  25224. });
  25225. Object.defineProperty(ValueCondition, "IsDifferent", {
  25226. get: function () {
  25227. return ValueCondition._IsDifferent;
  25228. },
  25229. enumerable: true,
  25230. configurable: true
  25231. });
  25232. Object.defineProperty(ValueCondition, "IsGreater", {
  25233. get: function () {
  25234. return ValueCondition._IsGreater;
  25235. },
  25236. enumerable: true,
  25237. configurable: true
  25238. });
  25239. Object.defineProperty(ValueCondition, "IsLesser", {
  25240. get: function () {
  25241. return ValueCondition._IsLesser;
  25242. },
  25243. enumerable: true,
  25244. configurable: true
  25245. });
  25246. // Methods
  25247. ValueCondition.prototype.isValid = function () {
  25248. switch (this.operator) {
  25249. case ValueCondition.IsGreater:
  25250. return this._target[this._property] > this.value;
  25251. case ValueCondition.IsLesser:
  25252. return this._target[this._property] < this.value;
  25253. case ValueCondition.IsEqual:
  25254. case ValueCondition.IsDifferent:
  25255. var check;
  25256. if (this.value.equals) {
  25257. check = this.value.equals(this._target[this._property]);
  25258. }
  25259. else {
  25260. check = this.value === this._target[this._property];
  25261. }
  25262. return this.operator === ValueCondition.IsEqual ? check : !check;
  25263. }
  25264. return false;
  25265. };
  25266. // Statics
  25267. ValueCondition._IsEqual = 0;
  25268. ValueCondition._IsDifferent = 1;
  25269. ValueCondition._IsGreater = 2;
  25270. ValueCondition._IsLesser = 3;
  25271. return ValueCondition;
  25272. })(Condition);
  25273. BABYLON.ValueCondition = ValueCondition;
  25274. var PredicateCondition = (function (_super) {
  25275. __extends(PredicateCondition, _super);
  25276. function PredicateCondition(actionManager, predicate) {
  25277. _super.call(this, actionManager);
  25278. this.predicate = predicate;
  25279. }
  25280. PredicateCondition.prototype.isValid = function () {
  25281. return this.predicate();
  25282. };
  25283. return PredicateCondition;
  25284. })(Condition);
  25285. BABYLON.PredicateCondition = PredicateCondition;
  25286. var StateCondition = (function (_super) {
  25287. __extends(StateCondition, _super);
  25288. function StateCondition(actionManager, target, value) {
  25289. _super.call(this, actionManager);
  25290. this.value = value;
  25291. this._target = target;
  25292. }
  25293. // Methods
  25294. StateCondition.prototype.isValid = function () {
  25295. return this._target.state === this.value;
  25296. };
  25297. return StateCondition;
  25298. })(Condition);
  25299. BABYLON.StateCondition = StateCondition;
  25300. })(BABYLON || (BABYLON = {}));
  25301. var BABYLON;
  25302. (function (BABYLON) {
  25303. var Action = (function () {
  25304. function Action(triggerOptions, condition) {
  25305. this.triggerOptions = triggerOptions;
  25306. if (triggerOptions.parameter) {
  25307. this.trigger = triggerOptions.trigger;
  25308. this._triggerParameter = triggerOptions.parameter;
  25309. }
  25310. else {
  25311. this.trigger = triggerOptions;
  25312. }
  25313. this._nextActiveAction = this;
  25314. this._condition = condition;
  25315. }
  25316. // Methods
  25317. Action.prototype._prepare = function () {
  25318. };
  25319. Action.prototype.getTriggerParameter = function () {
  25320. return this._triggerParameter;
  25321. };
  25322. Action.prototype._executeCurrent = function (evt) {
  25323. if (this._nextActiveAction._condition) {
  25324. var condition = this._nextActiveAction._condition;
  25325. var currentRenderId = this._actionManager.getScene().getRenderId();
  25326. // We cache the current evaluation for the current frame
  25327. if (condition._evaluationId === currentRenderId) {
  25328. if (!condition._currentResult) {
  25329. return;
  25330. }
  25331. }
  25332. else {
  25333. condition._evaluationId = currentRenderId;
  25334. if (!condition.isValid()) {
  25335. condition._currentResult = false;
  25336. return;
  25337. }
  25338. condition._currentResult = true;
  25339. }
  25340. }
  25341. this._nextActiveAction.execute(evt);
  25342. if (this._nextActiveAction._child) {
  25343. if (!this._nextActiveAction._child._actionManager) {
  25344. this._nextActiveAction._child._actionManager = this._actionManager;
  25345. }
  25346. this._nextActiveAction = this._nextActiveAction._child;
  25347. }
  25348. else {
  25349. this._nextActiveAction = this;
  25350. }
  25351. };
  25352. Action.prototype.execute = function (evt) {
  25353. };
  25354. Action.prototype.then = function (action) {
  25355. this._child = action;
  25356. action._actionManager = this._actionManager;
  25357. action._prepare();
  25358. return action;
  25359. };
  25360. Action.prototype._getProperty = function (propertyPath) {
  25361. return this._actionManager._getProperty(propertyPath);
  25362. };
  25363. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25364. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25365. };
  25366. return Action;
  25367. })();
  25368. BABYLON.Action = Action;
  25369. })(BABYLON || (BABYLON = {}));
  25370. var BABYLON;
  25371. (function (BABYLON) {
  25372. /**
  25373. * ActionEvent is the event beint sent when an action is triggered.
  25374. */
  25375. var ActionEvent = (function () {
  25376. /**
  25377. * @constructor
  25378. * @param source The mesh or sprite that triggered the action.
  25379. * @param pointerX The X mouse cursor position at the time of the event
  25380. * @param pointerY The Y mouse cursor position at the time of the event
  25381. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25382. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25383. */
  25384. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25385. this.source = source;
  25386. this.pointerX = pointerX;
  25387. this.pointerY = pointerY;
  25388. this.meshUnderPointer = meshUnderPointer;
  25389. this.sourceEvent = sourceEvent;
  25390. this.additionalData = additionalData;
  25391. }
  25392. /**
  25393. * Helper function to auto-create an ActionEvent from a source mesh.
  25394. * @param source The source mesh that triggered the event
  25395. * @param evt {Event} The original (browser) event
  25396. */
  25397. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25398. var scene = source.getScene();
  25399. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25400. };
  25401. /**
  25402. * Helper function to auto-create an ActionEvent from a source mesh.
  25403. * @param source The source sprite that triggered the event
  25404. * @param scene Scene associated with the sprite
  25405. * @param evt {Event} The original (browser) event
  25406. */
  25407. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25408. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25409. };
  25410. /**
  25411. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25412. * @param scene the scene where the event occurred
  25413. * @param evt {Event} The original (browser) event
  25414. */
  25415. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25416. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25417. };
  25418. return ActionEvent;
  25419. })();
  25420. BABYLON.ActionEvent = ActionEvent;
  25421. /**
  25422. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25423. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25424. */
  25425. var ActionManager = (function () {
  25426. function ActionManager(scene) {
  25427. // Members
  25428. this.actions = new Array();
  25429. this._scene = scene;
  25430. scene._actionManagers.push(this);
  25431. }
  25432. Object.defineProperty(ActionManager, "NothingTrigger", {
  25433. get: function () {
  25434. return ActionManager._NothingTrigger;
  25435. },
  25436. enumerable: true,
  25437. configurable: true
  25438. });
  25439. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25440. get: function () {
  25441. return ActionManager._OnPickTrigger;
  25442. },
  25443. enumerable: true,
  25444. configurable: true
  25445. });
  25446. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25447. get: function () {
  25448. return ActionManager._OnLeftPickTrigger;
  25449. },
  25450. enumerable: true,
  25451. configurable: true
  25452. });
  25453. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25454. get: function () {
  25455. return ActionManager._OnRightPickTrigger;
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25461. get: function () {
  25462. return ActionManager._OnCenterPickTrigger;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25468. get: function () {
  25469. return ActionManager._OnPointerOverTrigger;
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25475. get: function () {
  25476. return ActionManager._OnPointerOutTrigger;
  25477. },
  25478. enumerable: true,
  25479. configurable: true
  25480. });
  25481. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25482. get: function () {
  25483. return ActionManager._OnEveryFrameTrigger;
  25484. },
  25485. enumerable: true,
  25486. configurable: true
  25487. });
  25488. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25489. get: function () {
  25490. return ActionManager._OnIntersectionEnterTrigger;
  25491. },
  25492. enumerable: true,
  25493. configurable: true
  25494. });
  25495. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25496. get: function () {
  25497. return ActionManager._OnIntersectionExitTrigger;
  25498. },
  25499. enumerable: true,
  25500. configurable: true
  25501. });
  25502. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25503. get: function () {
  25504. return ActionManager._OnKeyDownTrigger;
  25505. },
  25506. enumerable: true,
  25507. configurable: true
  25508. });
  25509. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25510. get: function () {
  25511. return ActionManager._OnKeyUpTrigger;
  25512. },
  25513. enumerable: true,
  25514. configurable: true
  25515. });
  25516. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25517. get: function () {
  25518. return ActionManager._OnPickUpTrigger;
  25519. },
  25520. enumerable: true,
  25521. configurable: true
  25522. });
  25523. // Methods
  25524. ActionManager.prototype.dispose = function () {
  25525. var index = this._scene._actionManagers.indexOf(this);
  25526. if (index > -1) {
  25527. this._scene._actionManagers.splice(index, 1);
  25528. }
  25529. };
  25530. ActionManager.prototype.getScene = function () {
  25531. return this._scene;
  25532. };
  25533. /**
  25534. * Does this action manager handles actions of any of the given triggers
  25535. * @param {number[]} triggers - the triggers to be tested
  25536. * @return {boolean} whether one (or more) of the triggers is handeled
  25537. */
  25538. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25539. for (var index = 0; index < this.actions.length; index++) {
  25540. var action = this.actions[index];
  25541. if (triggers.indexOf(action.trigger) > -1) {
  25542. return true;
  25543. }
  25544. }
  25545. return false;
  25546. };
  25547. /**
  25548. * Does this action manager handles actions of a given trigger
  25549. * @param {number} trigger - the trigger to be tested
  25550. * @return {boolean} whether the trigger is handeled
  25551. */
  25552. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25553. for (var index = 0; index < this.actions.length; index++) {
  25554. var action = this.actions[index];
  25555. if (action.trigger === trigger) {
  25556. return true;
  25557. }
  25558. }
  25559. return false;
  25560. };
  25561. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25562. /**
  25563. * Does this action manager has pointer triggers
  25564. * @return {boolean} whether or not it has pointer triggers
  25565. */
  25566. get: function () {
  25567. for (var index = 0; index < this.actions.length; index++) {
  25568. var action = this.actions[index];
  25569. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25570. return true;
  25571. }
  25572. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25573. return true;
  25574. }
  25575. }
  25576. return false;
  25577. },
  25578. enumerable: true,
  25579. configurable: true
  25580. });
  25581. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25582. /**
  25583. * Does this action manager has pick triggers
  25584. * @return {boolean} whether or not it has pick triggers
  25585. */
  25586. get: function () {
  25587. for (var index = 0; index < this.actions.length; index++) {
  25588. var action = this.actions[index];
  25589. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25590. return true;
  25591. }
  25592. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25593. return true;
  25594. }
  25595. }
  25596. return false;
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. /**
  25602. * Registers an action to this action manager
  25603. * @param {BABYLON.Action} action - the action to be registered
  25604. * @return {BABYLON.Action} the action amended (prepared) after registration
  25605. */
  25606. ActionManager.prototype.registerAction = function (action) {
  25607. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25608. if (this.getScene().actionManager !== this) {
  25609. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25610. return null;
  25611. }
  25612. }
  25613. this.actions.push(action);
  25614. action._actionManager = this;
  25615. action._prepare();
  25616. return action;
  25617. };
  25618. /**
  25619. * Process a specific trigger
  25620. * @param {number} trigger - the trigger to process
  25621. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25622. */
  25623. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25624. for (var index = 0; index < this.actions.length; index++) {
  25625. var action = this.actions[index];
  25626. if (action.trigger === trigger) {
  25627. if (trigger === ActionManager.OnKeyUpTrigger
  25628. || trigger === ActionManager.OnKeyDownTrigger) {
  25629. var parameter = action.getTriggerParameter();
  25630. if (parameter) {
  25631. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25632. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25633. if (actualkey !== parameter.toLowerCase()) {
  25634. continue;
  25635. }
  25636. }
  25637. }
  25638. action._executeCurrent(evt);
  25639. }
  25640. }
  25641. };
  25642. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25643. var properties = propertyPath.split(".");
  25644. for (var index = 0; index < properties.length - 1; index++) {
  25645. target = target[properties[index]];
  25646. }
  25647. return target;
  25648. };
  25649. ActionManager.prototype._getProperty = function (propertyPath) {
  25650. var properties = propertyPath.split(".");
  25651. return properties[properties.length - 1];
  25652. };
  25653. // Statics
  25654. ActionManager._NothingTrigger = 0;
  25655. ActionManager._OnPickTrigger = 1;
  25656. ActionManager._OnLeftPickTrigger = 2;
  25657. ActionManager._OnRightPickTrigger = 3;
  25658. ActionManager._OnCenterPickTrigger = 4;
  25659. ActionManager._OnPointerOverTrigger = 5;
  25660. ActionManager._OnPointerOutTrigger = 6;
  25661. ActionManager._OnEveryFrameTrigger = 7;
  25662. ActionManager._OnIntersectionEnterTrigger = 8;
  25663. ActionManager._OnIntersectionExitTrigger = 9;
  25664. ActionManager._OnKeyDownTrigger = 10;
  25665. ActionManager._OnKeyUpTrigger = 11;
  25666. ActionManager._OnPickUpTrigger = 12;
  25667. return ActionManager;
  25668. })();
  25669. BABYLON.ActionManager = ActionManager;
  25670. })(BABYLON || (BABYLON = {}));
  25671. var BABYLON;
  25672. (function (BABYLON) {
  25673. var InterpolateValueAction = (function (_super) {
  25674. __extends(InterpolateValueAction, _super);
  25675. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25676. if (duration === void 0) { duration = 1000; }
  25677. _super.call(this, triggerOptions, condition);
  25678. this.propertyPath = propertyPath;
  25679. this.value = value;
  25680. this.duration = duration;
  25681. this.stopOtherAnimations = stopOtherAnimations;
  25682. this.onInterpolationDone = onInterpolationDone;
  25683. this._target = target;
  25684. }
  25685. InterpolateValueAction.prototype._prepare = function () {
  25686. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25687. this._property = this._getProperty(this.propertyPath);
  25688. };
  25689. InterpolateValueAction.prototype.execute = function () {
  25690. var scene = this._actionManager.getScene();
  25691. var keys = [
  25692. {
  25693. frame: 0,
  25694. value: this._target[this._property]
  25695. }, {
  25696. frame: 100,
  25697. value: this.value
  25698. }
  25699. ];
  25700. var dataType;
  25701. if (typeof this.value === "number") {
  25702. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25703. }
  25704. else if (this.value instanceof BABYLON.Color3) {
  25705. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25706. }
  25707. else if (this.value instanceof BABYLON.Vector3) {
  25708. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25709. }
  25710. else if (this.value instanceof BABYLON.Matrix) {
  25711. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25712. }
  25713. else if (this.value instanceof BABYLON.Quaternion) {
  25714. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25715. }
  25716. else {
  25717. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25718. return;
  25719. }
  25720. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25721. animation.setKeys(keys);
  25722. if (this.stopOtherAnimations) {
  25723. scene.stopAnimation(this._target);
  25724. }
  25725. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25726. };
  25727. return InterpolateValueAction;
  25728. })(BABYLON.Action);
  25729. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25730. })(BABYLON || (BABYLON = {}));
  25731. var BABYLON;
  25732. (function (BABYLON) {
  25733. var SwitchBooleanAction = (function (_super) {
  25734. __extends(SwitchBooleanAction, _super);
  25735. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25736. _super.call(this, triggerOptions, condition);
  25737. this.propertyPath = propertyPath;
  25738. this._target = target;
  25739. }
  25740. SwitchBooleanAction.prototype._prepare = function () {
  25741. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25742. this._property = this._getProperty(this.propertyPath);
  25743. };
  25744. SwitchBooleanAction.prototype.execute = function () {
  25745. this._target[this._property] = !this._target[this._property];
  25746. };
  25747. return SwitchBooleanAction;
  25748. })(BABYLON.Action);
  25749. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25750. var SetStateAction = (function (_super) {
  25751. __extends(SetStateAction, _super);
  25752. function SetStateAction(triggerOptions, target, value, condition) {
  25753. _super.call(this, triggerOptions, condition);
  25754. this.value = value;
  25755. this._target = target;
  25756. }
  25757. SetStateAction.prototype.execute = function () {
  25758. this._target.state = this.value;
  25759. };
  25760. return SetStateAction;
  25761. })(BABYLON.Action);
  25762. BABYLON.SetStateAction = SetStateAction;
  25763. var SetValueAction = (function (_super) {
  25764. __extends(SetValueAction, _super);
  25765. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25766. _super.call(this, triggerOptions, condition);
  25767. this.propertyPath = propertyPath;
  25768. this.value = value;
  25769. this._target = target;
  25770. }
  25771. SetValueAction.prototype._prepare = function () {
  25772. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25773. this._property = this._getProperty(this.propertyPath);
  25774. };
  25775. SetValueAction.prototype.execute = function () {
  25776. this._target[this._property] = this.value;
  25777. };
  25778. return SetValueAction;
  25779. })(BABYLON.Action);
  25780. BABYLON.SetValueAction = SetValueAction;
  25781. var IncrementValueAction = (function (_super) {
  25782. __extends(IncrementValueAction, _super);
  25783. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25784. _super.call(this, triggerOptions, condition);
  25785. this.propertyPath = propertyPath;
  25786. this.value = value;
  25787. this._target = target;
  25788. }
  25789. IncrementValueAction.prototype._prepare = function () {
  25790. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25791. this._property = this._getProperty(this.propertyPath);
  25792. if (typeof this._target[this._property] !== "number") {
  25793. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25794. }
  25795. };
  25796. IncrementValueAction.prototype.execute = function () {
  25797. this._target[this._property] += this.value;
  25798. };
  25799. return IncrementValueAction;
  25800. })(BABYLON.Action);
  25801. BABYLON.IncrementValueAction = IncrementValueAction;
  25802. var PlayAnimationAction = (function (_super) {
  25803. __extends(PlayAnimationAction, _super);
  25804. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25805. _super.call(this, triggerOptions, condition);
  25806. this.from = from;
  25807. this.to = to;
  25808. this.loop = loop;
  25809. this._target = target;
  25810. }
  25811. PlayAnimationAction.prototype._prepare = function () {
  25812. };
  25813. PlayAnimationAction.prototype.execute = function () {
  25814. var scene = this._actionManager.getScene();
  25815. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25816. };
  25817. return PlayAnimationAction;
  25818. })(BABYLON.Action);
  25819. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25820. var StopAnimationAction = (function (_super) {
  25821. __extends(StopAnimationAction, _super);
  25822. function StopAnimationAction(triggerOptions, target, condition) {
  25823. _super.call(this, triggerOptions, condition);
  25824. this._target = target;
  25825. }
  25826. StopAnimationAction.prototype._prepare = function () {
  25827. };
  25828. StopAnimationAction.prototype.execute = function () {
  25829. var scene = this._actionManager.getScene();
  25830. scene.stopAnimation(this._target);
  25831. };
  25832. return StopAnimationAction;
  25833. })(BABYLON.Action);
  25834. BABYLON.StopAnimationAction = StopAnimationAction;
  25835. var DoNothingAction = (function (_super) {
  25836. __extends(DoNothingAction, _super);
  25837. function DoNothingAction(triggerOptions, condition) {
  25838. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25839. _super.call(this, triggerOptions, condition);
  25840. }
  25841. DoNothingAction.prototype.execute = function () {
  25842. };
  25843. return DoNothingAction;
  25844. })(BABYLON.Action);
  25845. BABYLON.DoNothingAction = DoNothingAction;
  25846. var CombineAction = (function (_super) {
  25847. __extends(CombineAction, _super);
  25848. function CombineAction(triggerOptions, children, condition) {
  25849. _super.call(this, triggerOptions, condition);
  25850. this.children = children;
  25851. }
  25852. CombineAction.prototype._prepare = function () {
  25853. for (var index = 0; index < this.children.length; index++) {
  25854. this.children[index]._actionManager = this._actionManager;
  25855. this.children[index]._prepare();
  25856. }
  25857. };
  25858. CombineAction.prototype.execute = function (evt) {
  25859. for (var index = 0; index < this.children.length; index++) {
  25860. this.children[index].execute(evt);
  25861. }
  25862. };
  25863. return CombineAction;
  25864. })(BABYLON.Action);
  25865. BABYLON.CombineAction = CombineAction;
  25866. var ExecuteCodeAction = (function (_super) {
  25867. __extends(ExecuteCodeAction, _super);
  25868. function ExecuteCodeAction(triggerOptions, func, condition) {
  25869. _super.call(this, triggerOptions, condition);
  25870. this.func = func;
  25871. }
  25872. ExecuteCodeAction.prototype.execute = function (evt) {
  25873. this.func(evt);
  25874. };
  25875. return ExecuteCodeAction;
  25876. })(BABYLON.Action);
  25877. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25878. var SetParentAction = (function (_super) {
  25879. __extends(SetParentAction, _super);
  25880. function SetParentAction(triggerOptions, target, parent, condition) {
  25881. _super.call(this, triggerOptions, condition);
  25882. this._target = target;
  25883. this._parent = parent;
  25884. }
  25885. SetParentAction.prototype._prepare = function () {
  25886. };
  25887. SetParentAction.prototype.execute = function () {
  25888. if (this._target.parent === this._parent) {
  25889. return;
  25890. }
  25891. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25892. invertParentWorldMatrix.invert();
  25893. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25894. this._target.parent = this._parent;
  25895. };
  25896. return SetParentAction;
  25897. })(BABYLON.Action);
  25898. BABYLON.SetParentAction = SetParentAction;
  25899. var PlaySoundAction = (function (_super) {
  25900. __extends(PlaySoundAction, _super);
  25901. function PlaySoundAction(triggerOptions, sound, condition) {
  25902. _super.call(this, triggerOptions, condition);
  25903. this._sound = sound;
  25904. }
  25905. PlaySoundAction.prototype._prepare = function () {
  25906. };
  25907. PlaySoundAction.prototype.execute = function () {
  25908. if (this._sound !== undefined)
  25909. this._sound.play();
  25910. };
  25911. return PlaySoundAction;
  25912. })(BABYLON.Action);
  25913. BABYLON.PlaySoundAction = PlaySoundAction;
  25914. var StopSoundAction = (function (_super) {
  25915. __extends(StopSoundAction, _super);
  25916. function StopSoundAction(triggerOptions, sound, condition) {
  25917. _super.call(this, triggerOptions, condition);
  25918. this._sound = sound;
  25919. }
  25920. StopSoundAction.prototype._prepare = function () {
  25921. };
  25922. StopSoundAction.prototype.execute = function () {
  25923. if (this._sound !== undefined)
  25924. this._sound.stop();
  25925. };
  25926. return StopSoundAction;
  25927. })(BABYLON.Action);
  25928. BABYLON.StopSoundAction = StopSoundAction;
  25929. })(BABYLON || (BABYLON = {}));
  25930. var BABYLON;
  25931. (function (BABYLON) {
  25932. var Geometry = (function () {
  25933. function Geometry(id, scene, vertexData, updatable, mesh) {
  25934. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25935. this._totalVertices = 0;
  25936. this._isDisposed = false;
  25937. this.id = id;
  25938. this._engine = scene.getEngine();
  25939. this._meshes = [];
  25940. this._scene = scene;
  25941. //Init vertex buffer cache
  25942. this._vertexBuffers = {};
  25943. this._indices = [];
  25944. // vertexData
  25945. if (vertexData) {
  25946. this.setAllVerticesData(vertexData, updatable);
  25947. }
  25948. else {
  25949. this._totalVertices = 0;
  25950. this._indices = [];
  25951. }
  25952. // applyToMesh
  25953. if (mesh) {
  25954. this.applyToMesh(mesh);
  25955. mesh.computeWorldMatrix(true);
  25956. }
  25957. }
  25958. Object.defineProperty(Geometry.prototype, "extend", {
  25959. get: function () {
  25960. return this._extend;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. Geometry.prototype.getScene = function () {
  25966. return this._scene;
  25967. };
  25968. Geometry.prototype.getEngine = function () {
  25969. return this._engine;
  25970. };
  25971. Geometry.prototype.isReady = function () {
  25972. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25973. };
  25974. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25975. vertexData.applyToGeometry(this, updatable);
  25976. this.notifyUpdate();
  25977. };
  25978. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25979. if (this._vertexBuffers[kind]) {
  25980. this._vertexBuffers[kind].dispose();
  25981. }
  25982. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25983. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25984. stride = this._vertexBuffers[kind].getStrideSize();
  25985. this._totalVertices = data.length / stride;
  25986. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25987. var meshes = this._meshes;
  25988. var numOfMeshes = meshes.length;
  25989. for (var index = 0; index < numOfMeshes; index++) {
  25990. var mesh = meshes[index];
  25991. mesh._resetPointsArrayCache();
  25992. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25993. mesh._createGlobalSubMesh();
  25994. mesh.computeWorldMatrix(true);
  25995. }
  25996. }
  25997. this.notifyUpdate(kind);
  25998. };
  25999. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26000. var vertexBuffer = this.getVertexBuffer(kind);
  26001. if (!vertexBuffer) {
  26002. return;
  26003. }
  26004. vertexBuffer.updateDirectly(data, offset);
  26005. this.notifyUpdate(kind);
  26006. };
  26007. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26008. var vertexBuffer = this.getVertexBuffer(kind);
  26009. if (!vertexBuffer) {
  26010. return;
  26011. }
  26012. vertexBuffer.update(data);
  26013. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26014. var stride = vertexBuffer.getStrideSize();
  26015. this._totalVertices = data.length / stride;
  26016. if (updateExtends) {
  26017. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26018. }
  26019. var meshes = this._meshes;
  26020. var numOfMeshes = meshes.length;
  26021. for (var index = 0; index < numOfMeshes; index++) {
  26022. var mesh = meshes[index];
  26023. mesh._resetPointsArrayCache();
  26024. if (updateExtends) {
  26025. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26026. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26027. var subMesh = mesh.subMeshes[subIndex];
  26028. subMesh.refreshBoundingInfo();
  26029. }
  26030. }
  26031. }
  26032. }
  26033. this.notifyUpdate(kind);
  26034. };
  26035. Geometry.prototype.getTotalVertices = function () {
  26036. if (!this.isReady()) {
  26037. return 0;
  26038. }
  26039. return this._totalVertices;
  26040. };
  26041. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26042. var vertexBuffer = this.getVertexBuffer(kind);
  26043. if (!vertexBuffer) {
  26044. return null;
  26045. }
  26046. var orig = vertexBuffer.getData();
  26047. if (!copyWhenShared || this._meshes.length === 1) {
  26048. return orig;
  26049. }
  26050. else {
  26051. var len = orig.length;
  26052. var copy = [];
  26053. for (var i = 0; i < len; i++) {
  26054. copy.push(orig[i]);
  26055. }
  26056. return copy;
  26057. }
  26058. };
  26059. Geometry.prototype.getVertexBuffer = function (kind) {
  26060. if (!this.isReady()) {
  26061. return null;
  26062. }
  26063. return this._vertexBuffers[kind];
  26064. };
  26065. Geometry.prototype.getVertexBuffers = function () {
  26066. if (!this.isReady()) {
  26067. return null;
  26068. }
  26069. return this._vertexBuffers;
  26070. };
  26071. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26072. if (!this._vertexBuffers) {
  26073. if (this._delayInfo) {
  26074. return this._delayInfo.indexOf(kind) !== -1;
  26075. }
  26076. return false;
  26077. }
  26078. return this._vertexBuffers[kind] !== undefined;
  26079. };
  26080. Geometry.prototype.getVerticesDataKinds = function () {
  26081. var result = [];
  26082. var kind;
  26083. if (!this._vertexBuffers && this._delayInfo) {
  26084. for (kind in this._delayInfo) {
  26085. result.push(kind);
  26086. }
  26087. }
  26088. else {
  26089. for (kind in this._vertexBuffers) {
  26090. result.push(kind);
  26091. }
  26092. }
  26093. return result;
  26094. };
  26095. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26096. if (this._indexBuffer) {
  26097. this._engine._releaseBuffer(this._indexBuffer);
  26098. }
  26099. this._indices = indices;
  26100. if (this._meshes.length !== 0 && this._indices) {
  26101. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26102. }
  26103. if (totalVertices !== undefined) {
  26104. this._totalVertices = totalVertices;
  26105. }
  26106. var meshes = this._meshes;
  26107. var numOfMeshes = meshes.length;
  26108. for (var index = 0; index < numOfMeshes; index++) {
  26109. meshes[index]._createGlobalSubMesh();
  26110. }
  26111. this.notifyUpdate();
  26112. };
  26113. Geometry.prototype.getTotalIndices = function () {
  26114. if (!this.isReady()) {
  26115. return 0;
  26116. }
  26117. return this._indices.length;
  26118. };
  26119. Geometry.prototype.getIndices = function (copyWhenShared) {
  26120. if (!this.isReady()) {
  26121. return null;
  26122. }
  26123. var orig = this._indices;
  26124. if (!copyWhenShared || this._meshes.length === 1) {
  26125. return orig;
  26126. }
  26127. else {
  26128. var len = orig.length;
  26129. var copy = [];
  26130. for (var i = 0; i < len; i++) {
  26131. copy.push(orig[i]);
  26132. }
  26133. return copy;
  26134. }
  26135. };
  26136. Geometry.prototype.getIndexBuffer = function () {
  26137. if (!this.isReady()) {
  26138. return null;
  26139. }
  26140. return this._indexBuffer;
  26141. };
  26142. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26143. var meshes = this._meshes;
  26144. var index = meshes.indexOf(mesh);
  26145. if (index === -1) {
  26146. return;
  26147. }
  26148. for (var kind in this._vertexBuffers) {
  26149. this._vertexBuffers[kind].dispose();
  26150. }
  26151. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26152. this._indexBuffer = null;
  26153. }
  26154. meshes.splice(index, 1);
  26155. mesh._geometry = null;
  26156. if (meshes.length === 0 && shouldDispose) {
  26157. this.dispose();
  26158. }
  26159. };
  26160. Geometry.prototype.applyToMesh = function (mesh) {
  26161. if (mesh._geometry === this) {
  26162. return;
  26163. }
  26164. var previousGeometry = mesh._geometry;
  26165. if (previousGeometry) {
  26166. previousGeometry.releaseForMesh(mesh);
  26167. }
  26168. var meshes = this._meshes;
  26169. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26170. mesh._geometry = this;
  26171. this._scene.pushGeometry(this);
  26172. meshes.push(mesh);
  26173. if (this.isReady()) {
  26174. this._applyToMesh(mesh);
  26175. }
  26176. else {
  26177. mesh._boundingInfo = this._boundingInfo;
  26178. }
  26179. };
  26180. Geometry.prototype._applyToMesh = function (mesh) {
  26181. var numOfMeshes = this._meshes.length;
  26182. // vertexBuffers
  26183. for (var kind in this._vertexBuffers) {
  26184. if (numOfMeshes === 1) {
  26185. this._vertexBuffers[kind].create();
  26186. }
  26187. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26188. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26189. mesh._resetPointsArrayCache();
  26190. if (!this._extend) {
  26191. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26192. }
  26193. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26194. mesh._createGlobalSubMesh();
  26195. //bounding info was just created again, world matrix should be applied again.
  26196. mesh._updateBoundingInfo();
  26197. }
  26198. }
  26199. // indexBuffer
  26200. if (numOfMeshes === 1 && this._indices) {
  26201. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26202. }
  26203. if (this._indexBuffer) {
  26204. this._indexBuffer.references = numOfMeshes;
  26205. }
  26206. };
  26207. Geometry.prototype.notifyUpdate = function (kind) {
  26208. if (this.onGeometryUpdated) {
  26209. this.onGeometryUpdated(this, kind);
  26210. }
  26211. };
  26212. Geometry.prototype.load = function (scene, onLoaded) {
  26213. var _this = this;
  26214. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26215. return;
  26216. }
  26217. if (this.isReady()) {
  26218. if (onLoaded) {
  26219. onLoaded();
  26220. }
  26221. return;
  26222. }
  26223. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26224. scene._addPendingData(this);
  26225. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26226. _this._delayLoadingFunction(JSON.parse(data), _this);
  26227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26228. _this._delayInfo = [];
  26229. scene._removePendingData(_this);
  26230. var meshes = _this._meshes;
  26231. var numOfMeshes = meshes.length;
  26232. for (var index = 0; index < numOfMeshes; index++) {
  26233. _this._applyToMesh(meshes[index]);
  26234. }
  26235. if (onLoaded) {
  26236. onLoaded();
  26237. }
  26238. }, function () { }, scene.database);
  26239. };
  26240. Geometry.prototype.isDisposed = function () {
  26241. return this._isDisposed;
  26242. };
  26243. Geometry.prototype.dispose = function () {
  26244. var meshes = this._meshes;
  26245. var numOfMeshes = meshes.length;
  26246. var index;
  26247. for (index = 0; index < numOfMeshes; index++) {
  26248. this.releaseForMesh(meshes[index]);
  26249. }
  26250. this._meshes = [];
  26251. for (var kind in this._vertexBuffers) {
  26252. this._vertexBuffers[kind].dispose();
  26253. }
  26254. this._vertexBuffers = [];
  26255. this._totalVertices = 0;
  26256. if (this._indexBuffer) {
  26257. this._engine._releaseBuffer(this._indexBuffer);
  26258. }
  26259. this._indexBuffer = null;
  26260. this._indices = [];
  26261. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26262. this.delayLoadingFile = null;
  26263. this._delayLoadingFunction = null;
  26264. this._delayInfo = [];
  26265. this._boundingInfo = null;
  26266. this._scene.removeGeometry(this);
  26267. this._isDisposed = true;
  26268. };
  26269. Geometry.prototype.copy = function (id) {
  26270. var vertexData = new BABYLON.VertexData();
  26271. vertexData.indices = [];
  26272. var indices = this.getIndices();
  26273. for (var index = 0; index < indices.length; index++) {
  26274. vertexData.indices.push(indices[index]);
  26275. }
  26276. var updatable = false;
  26277. var stopChecking = false;
  26278. var kind;
  26279. for (kind in this._vertexBuffers) {
  26280. // using slice() to make a copy of the array and not just reference it
  26281. var data = this.getVerticesData(kind);
  26282. if (data instanceof Float32Array) {
  26283. vertexData.set(new Float32Array(data), kind);
  26284. }
  26285. else {
  26286. vertexData.set(data.slice(0), kind);
  26287. }
  26288. if (!stopChecking) {
  26289. updatable = this.getVertexBuffer(kind).isUpdatable();
  26290. stopChecking = !updatable;
  26291. }
  26292. }
  26293. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26294. geometry.delayLoadState = this.delayLoadState;
  26295. geometry.delayLoadingFile = this.delayLoadingFile;
  26296. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26297. for (kind in this._delayInfo) {
  26298. geometry._delayInfo = geometry._delayInfo || [];
  26299. geometry._delayInfo.push(kind);
  26300. }
  26301. // Bounding info
  26302. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26303. return geometry;
  26304. };
  26305. // Statics
  26306. Geometry.ExtractFromMesh = function (mesh, id) {
  26307. var geometry = mesh._geometry;
  26308. if (!geometry) {
  26309. return null;
  26310. }
  26311. return geometry.copy(id);
  26312. };
  26313. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26314. // be aware Math.random() could cause collisions
  26315. Geometry.RandomId = function () {
  26316. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26317. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26318. return v.toString(16);
  26319. });
  26320. };
  26321. return Geometry;
  26322. })();
  26323. BABYLON.Geometry = Geometry;
  26324. /////// Primitives //////////////////////////////////////////////
  26325. var Geometry;
  26326. (function (Geometry) {
  26327. var Primitives;
  26328. (function (Primitives) {
  26329. /// Abstract class
  26330. var _Primitive = (function (_super) {
  26331. __extends(_Primitive, _super);
  26332. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26333. this._beingRegenerated = true;
  26334. this._canBeRegenerated = canBeRegenerated;
  26335. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26336. this._beingRegenerated = false;
  26337. }
  26338. _Primitive.prototype.canBeRegenerated = function () {
  26339. return this._canBeRegenerated;
  26340. };
  26341. _Primitive.prototype.regenerate = function () {
  26342. if (!this._canBeRegenerated) {
  26343. return;
  26344. }
  26345. this._beingRegenerated = true;
  26346. this.setAllVerticesData(this._regenerateVertexData(), false);
  26347. this._beingRegenerated = false;
  26348. };
  26349. _Primitive.prototype.asNewGeometry = function (id) {
  26350. return _super.prototype.copy.call(this, id);
  26351. };
  26352. // overrides
  26353. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26354. if (!this._beingRegenerated) {
  26355. return;
  26356. }
  26357. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26358. };
  26359. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26360. if (!this._beingRegenerated) {
  26361. return;
  26362. }
  26363. _super.prototype.setVerticesData.call(this, kind, data, false);
  26364. };
  26365. // to override
  26366. // protected
  26367. _Primitive.prototype._regenerateVertexData = function () {
  26368. throw new Error("Abstract method");
  26369. };
  26370. _Primitive.prototype.copy = function (id) {
  26371. throw new Error("Must be overriden in sub-classes.");
  26372. };
  26373. return _Primitive;
  26374. })(Geometry);
  26375. Primitives._Primitive = _Primitive;
  26376. var Ribbon = (function (_super) {
  26377. __extends(Ribbon, _super);
  26378. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26379. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26380. this.pathArray = pathArray;
  26381. this.closeArray = closeArray;
  26382. this.closePath = closePath;
  26383. this.offset = offset;
  26384. this.side = side;
  26385. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26386. }
  26387. Ribbon.prototype._regenerateVertexData = function () {
  26388. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26389. };
  26390. Ribbon.prototype.copy = function (id) {
  26391. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26392. };
  26393. return Ribbon;
  26394. })(_Primitive);
  26395. Primitives.Ribbon = Ribbon;
  26396. var Box = (function (_super) {
  26397. __extends(Box, _super);
  26398. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26399. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26400. this.size = size;
  26401. this.side = side;
  26402. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26403. }
  26404. Box.prototype._regenerateVertexData = function () {
  26405. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26406. };
  26407. Box.prototype.copy = function (id) {
  26408. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26409. };
  26410. return Box;
  26411. })(_Primitive);
  26412. Primitives.Box = Box;
  26413. var Sphere = (function (_super) {
  26414. __extends(Sphere, _super);
  26415. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26416. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26417. this.segments = segments;
  26418. this.diameter = diameter;
  26419. this.side = side;
  26420. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26421. }
  26422. Sphere.prototype._regenerateVertexData = function () {
  26423. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26424. };
  26425. Sphere.prototype.copy = function (id) {
  26426. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26427. };
  26428. return Sphere;
  26429. })(_Primitive);
  26430. Primitives.Sphere = Sphere;
  26431. var Disc = (function (_super) {
  26432. __extends(Disc, _super);
  26433. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26434. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26435. this.radius = radius;
  26436. this.tessellation = tessellation;
  26437. this.side = side;
  26438. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26439. }
  26440. Disc.prototype._regenerateVertexData = function () {
  26441. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26442. };
  26443. Disc.prototype.copy = function (id) {
  26444. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26445. };
  26446. return Disc;
  26447. })(_Primitive);
  26448. Primitives.Disc = Disc;
  26449. var Cylinder = (function (_super) {
  26450. __extends(Cylinder, _super);
  26451. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26452. if (subdivisions === void 0) { subdivisions = 1; }
  26453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26454. this.height = height;
  26455. this.diameterTop = diameterTop;
  26456. this.diameterBottom = diameterBottom;
  26457. this.tessellation = tessellation;
  26458. this.subdivisions = subdivisions;
  26459. this.side = side;
  26460. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26461. }
  26462. Cylinder.prototype._regenerateVertexData = function () {
  26463. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26464. };
  26465. Cylinder.prototype.copy = function (id) {
  26466. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26467. };
  26468. return Cylinder;
  26469. })(_Primitive);
  26470. Primitives.Cylinder = Cylinder;
  26471. var Torus = (function (_super) {
  26472. __extends(Torus, _super);
  26473. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26474. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26475. this.diameter = diameter;
  26476. this.thickness = thickness;
  26477. this.tessellation = tessellation;
  26478. this.side = side;
  26479. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26480. }
  26481. Torus.prototype._regenerateVertexData = function () {
  26482. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26483. };
  26484. Torus.prototype.copy = function (id) {
  26485. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26486. };
  26487. return Torus;
  26488. })(_Primitive);
  26489. Primitives.Torus = Torus;
  26490. var Ground = (function (_super) {
  26491. __extends(Ground, _super);
  26492. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26493. this.width = width;
  26494. this.height = height;
  26495. this.subdivisions = subdivisions;
  26496. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26497. }
  26498. Ground.prototype._regenerateVertexData = function () {
  26499. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26500. };
  26501. Ground.prototype.copy = function (id) {
  26502. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26503. };
  26504. return Ground;
  26505. })(_Primitive);
  26506. Primitives.Ground = Ground;
  26507. var TiledGround = (function (_super) {
  26508. __extends(TiledGround, _super);
  26509. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26510. this.xmin = xmin;
  26511. this.zmin = zmin;
  26512. this.xmax = xmax;
  26513. this.zmax = zmax;
  26514. this.subdivisions = subdivisions;
  26515. this.precision = precision;
  26516. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26517. }
  26518. TiledGround.prototype._regenerateVertexData = function () {
  26519. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26520. };
  26521. TiledGround.prototype.copy = function (id) {
  26522. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26523. };
  26524. return TiledGround;
  26525. })(_Primitive);
  26526. Primitives.TiledGround = TiledGround;
  26527. var Plane = (function (_super) {
  26528. __extends(Plane, _super);
  26529. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26530. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26531. this.size = size;
  26532. this.side = side;
  26533. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26534. }
  26535. Plane.prototype._regenerateVertexData = function () {
  26536. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26537. };
  26538. Plane.prototype.copy = function (id) {
  26539. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26540. };
  26541. return Plane;
  26542. })(_Primitive);
  26543. Primitives.Plane = Plane;
  26544. var TorusKnot = (function (_super) {
  26545. __extends(TorusKnot, _super);
  26546. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26547. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26548. this.radius = radius;
  26549. this.tube = tube;
  26550. this.radialSegments = radialSegments;
  26551. this.tubularSegments = tubularSegments;
  26552. this.p = p;
  26553. this.q = q;
  26554. this.side = side;
  26555. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26556. }
  26557. TorusKnot.prototype._regenerateVertexData = function () {
  26558. 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 });
  26559. };
  26560. TorusKnot.prototype.copy = function (id) {
  26561. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26562. };
  26563. return TorusKnot;
  26564. })(_Primitive);
  26565. Primitives.TorusKnot = TorusKnot;
  26566. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26567. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26568. })(BABYLON || (BABYLON = {}));
  26569. var BABYLON;
  26570. (function (BABYLON) {
  26571. var GroundMesh = (function (_super) {
  26572. __extends(GroundMesh, _super);
  26573. function GroundMesh(name, scene) {
  26574. _super.call(this, name, scene);
  26575. this.generateOctree = false;
  26576. this._worldInverse = new BABYLON.Matrix();
  26577. }
  26578. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26579. get: function () {
  26580. return this._subdivisions;
  26581. },
  26582. enumerable: true,
  26583. configurable: true
  26584. });
  26585. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26586. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26587. this._subdivisions = chunksCount;
  26588. this.subdivide(this._subdivisions);
  26589. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26590. };
  26591. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26592. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26593. this.getWorldMatrix().invertToRef(this._worldInverse);
  26594. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26595. var pickInfo = this.intersects(ray);
  26596. if (pickInfo.hit) {
  26597. return pickInfo.pickedPoint.y;
  26598. }
  26599. return 0;
  26600. };
  26601. return GroundMesh;
  26602. })(BABYLON.Mesh);
  26603. BABYLON.GroundMesh = GroundMesh;
  26604. })(BABYLON || (BABYLON = {}));
  26605. var BABYLON;
  26606. (function (BABYLON) {
  26607. var LinesMesh = (function (_super) {
  26608. __extends(LinesMesh, _super);
  26609. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26610. if (parent === void 0) { parent = null; }
  26611. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26612. this.color = new BABYLON.Color3(1, 1, 1);
  26613. this.alpha = 1;
  26614. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26615. attributes: ["position"],
  26616. uniforms: ["worldViewProjection", "color"],
  26617. needAlphaBlending: true
  26618. });
  26619. }
  26620. Object.defineProperty(LinesMesh.prototype, "material", {
  26621. get: function () {
  26622. return this._colorShader;
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26628. get: function () {
  26629. return false;
  26630. },
  26631. enumerable: true,
  26632. configurable: true
  26633. });
  26634. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26635. get: function () {
  26636. return false;
  26637. },
  26638. enumerable: true,
  26639. configurable: true
  26640. });
  26641. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26642. var engine = this.getScene().getEngine();
  26643. var indexToBind = this._geometry.getIndexBuffer();
  26644. // VBOs
  26645. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26646. // Color
  26647. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26648. };
  26649. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26650. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26651. return;
  26652. }
  26653. var engine = this.getScene().getEngine();
  26654. // Draw order
  26655. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26656. };
  26657. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26658. return null;
  26659. };
  26660. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26661. this._colorShader.dispose();
  26662. _super.prototype.dispose.call(this, doNotRecurse);
  26663. };
  26664. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26665. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26666. };
  26667. return LinesMesh;
  26668. })(BABYLON.Mesh);
  26669. BABYLON.LinesMesh = LinesMesh;
  26670. })(BABYLON || (BABYLON = {}));
  26671. var BABYLON;
  26672. (function (BABYLON) {
  26673. var DebugLayer = (function () {
  26674. function DebugLayer(scene) {
  26675. var _this = this;
  26676. this._transformationMatrix = BABYLON.Matrix.Identity();
  26677. this._enabled = false;
  26678. this._labelsEnabled = false;
  26679. this._displayStatistics = true;
  26680. this._displayTree = false;
  26681. this._displayLogs = false;
  26682. this._identityMatrix = BABYLON.Matrix.Identity();
  26683. this.axisRatio = 0.02;
  26684. this.accentColor = "orange";
  26685. this._scene = scene;
  26686. this._syncPositions = function () {
  26687. var engine = _this._scene.getEngine();
  26688. var canvasRect = engine.getRenderingCanvasClientRect();
  26689. if (_this._showUI) {
  26690. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26691. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26692. _this._statsDiv.style.width = "400px";
  26693. _this._statsDiv.style.height = "auto";
  26694. _this._statsSubsetDiv.style.maxHeight = "240px";
  26695. _this._optionsDiv.style.left = "0px";
  26696. _this._optionsDiv.style.top = "10px";
  26697. _this._optionsDiv.style.width = "200px";
  26698. _this._optionsDiv.style.height = "auto";
  26699. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26700. _this._logDiv.style.left = "0px";
  26701. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26702. _this._logDiv.style.width = "600px";
  26703. _this._logDiv.style.height = "160px";
  26704. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26705. _this._treeDiv.style.top = "10px";
  26706. _this._treeDiv.style.width = "300px";
  26707. _this._treeDiv.style.height = "auto";
  26708. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26709. }
  26710. _this._globalDiv.style.left = canvasRect.left + "px";
  26711. _this._globalDiv.style.top = canvasRect.top + "px";
  26712. _this._drawingCanvas.style.left = "0px";
  26713. _this._drawingCanvas.style.top = "0px";
  26714. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26715. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26716. var devicePixelRatio = window.devicePixelRatio || 1;
  26717. var context = _this._drawingContext;
  26718. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26719. context.mozBackingStorePixelRatio ||
  26720. context.msBackingStorePixelRatio ||
  26721. context.oBackingStorePixelRatio ||
  26722. context.backingStorePixelRatio || 1;
  26723. _this._ratio = devicePixelRatio / backingStoreRatio;
  26724. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26725. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26726. };
  26727. this._onCanvasClick = function (evt) {
  26728. _this._clickPosition = {
  26729. x: evt.clientX * _this._ratio,
  26730. y: evt.clientY * _this._ratio
  26731. };
  26732. };
  26733. this._syncUI = function () {
  26734. if (_this._showUI) {
  26735. if (_this._displayStatistics) {
  26736. _this._displayStats();
  26737. _this._statsDiv.style.display = "";
  26738. }
  26739. else {
  26740. _this._statsDiv.style.display = "none";
  26741. }
  26742. if (_this._displayLogs) {
  26743. _this._logDiv.style.display = "";
  26744. }
  26745. else {
  26746. _this._logDiv.style.display = "none";
  26747. }
  26748. if (_this._displayTree) {
  26749. _this._treeDiv.style.display = "";
  26750. if (_this._needToRefreshMeshesTree) {
  26751. _this._needToRefreshMeshesTree = false;
  26752. _this._refreshMeshesTreeContent();
  26753. }
  26754. }
  26755. else {
  26756. _this._treeDiv.style.display = "none";
  26757. }
  26758. }
  26759. };
  26760. this._syncData = function () {
  26761. if (_this._labelsEnabled || !_this._showUI) {
  26762. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26763. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26764. var engine = _this._scene.getEngine();
  26765. var viewport = _this._camera.viewport;
  26766. var globalViewport = viewport.toGlobal(engine);
  26767. // Meshes
  26768. var meshes = _this._camera.getActiveMeshes();
  26769. for (var index = 0; index < meshes.length; index++) {
  26770. var mesh = meshes.data[index];
  26771. var position = mesh.getBoundingInfo().boundingSphere.center;
  26772. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26773. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26774. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26775. }
  26776. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26777. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26778. }
  26779. }
  26780. // Cameras
  26781. var cameras = _this._scene.cameras;
  26782. for (index = 0; index < cameras.length; index++) {
  26783. var camera = cameras[index];
  26784. if (camera === _this._camera) {
  26785. continue;
  26786. }
  26787. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26788. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26789. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26790. _this._camera.detachControl(engine.getRenderingCanvas());
  26791. _this._camera = camera;
  26792. _this._camera.attachControl(engine.getRenderingCanvas());
  26793. }, function () { return "purple"; });
  26794. }
  26795. }
  26796. // Lights
  26797. var lights = _this._scene.lights;
  26798. for (index = 0; index < lights.length; index++) {
  26799. var light = lights[index];
  26800. if (light.position) {
  26801. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26802. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26803. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26804. light.setEnabled(!light.isEnabled());
  26805. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26806. }
  26807. }
  26808. }
  26809. }
  26810. _this._clickPosition = undefined;
  26811. };
  26812. }
  26813. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26814. while (this._treeSubsetDiv.hasChildNodes()) {
  26815. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26816. }
  26817. // Add meshes
  26818. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26819. sortedArray.sort(function (a, b) {
  26820. if (a.name === b.name) {
  26821. return 0;
  26822. }
  26823. return (a.name > b.name) ? 1 : -1;
  26824. });
  26825. for (var index = 0; index < sortedArray.length; index++) {
  26826. var mesh = sortedArray[index];
  26827. if (!mesh.isEnabled()) {
  26828. continue;
  26829. }
  26830. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26831. m.isVisible = element.checked;
  26832. }, mesh);
  26833. }
  26834. };
  26835. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26836. this._drawingContext.beginPath();
  26837. this._drawingContext.moveTo(zero.x, zero.y);
  26838. this._drawingContext.lineTo(unit.x, unit.y);
  26839. this._drawingContext.strokeStyle = color;
  26840. this._drawingContext.lineWidth = 4;
  26841. this._drawingContext.stroke();
  26842. this._drawingContext.font = "normal 14px Segoe UI";
  26843. this._drawingContext.fillStyle = color;
  26844. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26845. };
  26846. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26847. var position = mesh.getBoundingInfo().boundingSphere.center;
  26848. var worldMatrix = mesh.getWorldMatrix();
  26849. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26850. var unit = (unprojectedVector.subtract(position)).length();
  26851. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26852. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26853. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26854. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26855. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26856. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26857. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26858. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26859. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26860. };
  26861. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26862. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26863. this._drawingContext.font = "normal 12px Segoe UI";
  26864. var textMetrics = this._drawingContext.measureText(text);
  26865. var centerX = projectedPosition.x - textMetrics.width / 2;
  26866. var centerY = projectedPosition.y;
  26867. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26868. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26869. onClick();
  26870. }
  26871. this._drawingContext.beginPath();
  26872. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26873. this._drawingContext.fillStyle = getFillStyle();
  26874. this._drawingContext.globalAlpha = 0.5;
  26875. this._drawingContext.fill();
  26876. this._drawingContext.globalAlpha = 1.0;
  26877. this._drawingContext.strokeStyle = '#FFFFFF';
  26878. this._drawingContext.lineWidth = 1;
  26879. this._drawingContext.stroke();
  26880. this._drawingContext.fillStyle = "#FFFFFF";
  26881. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26882. this._drawingContext.beginPath();
  26883. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26884. this._drawingContext.fill();
  26885. }
  26886. };
  26887. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26888. if (!this._clickPosition) {
  26889. return false;
  26890. }
  26891. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26892. return false;
  26893. }
  26894. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26895. return false;
  26896. }
  26897. return true;
  26898. };
  26899. DebugLayer.prototype.isVisible = function () {
  26900. return this._enabled;
  26901. };
  26902. DebugLayer.prototype.hide = function () {
  26903. if (!this._enabled) {
  26904. return;
  26905. }
  26906. this._enabled = false;
  26907. var engine = this._scene.getEngine();
  26908. this._scene.unregisterBeforeRender(this._syncData);
  26909. this._scene.unregisterAfterRender(this._syncUI);
  26910. this._rootElement.removeChild(this._globalDiv);
  26911. this._scene.forceShowBoundingBoxes = false;
  26912. this._scene.forceWireframe = false;
  26913. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26914. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26915. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26916. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26917. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26918. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26919. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26920. BABYLON.StandardMaterial.LightmapEnabled = true;
  26921. this._scene.shadowsEnabled = true;
  26922. this._scene.particlesEnabled = true;
  26923. this._scene.postProcessesEnabled = true;
  26924. this._scene.collisionsEnabled = true;
  26925. this._scene.lightsEnabled = true;
  26926. this._scene.texturesEnabled = true;
  26927. this._scene.lensFlaresEnabled = true;
  26928. this._scene.proceduralTexturesEnabled = true;
  26929. this._scene.renderTargetsEnabled = true;
  26930. this._scene.probesEnabled = true;
  26931. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26932. };
  26933. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26934. if (showUI === void 0) { showUI = true; }
  26935. if (camera === void 0) { camera = null; }
  26936. if (rootElement === void 0) { rootElement = null; }
  26937. if (this._enabled) {
  26938. return;
  26939. }
  26940. this._enabled = true;
  26941. if (camera) {
  26942. this._camera = camera;
  26943. }
  26944. else {
  26945. this._camera = this._scene.activeCamera;
  26946. }
  26947. this._showUI = showUI;
  26948. var engine = this._scene.getEngine();
  26949. this._globalDiv = document.createElement("div");
  26950. this._rootElement = rootElement || document.body;
  26951. this._rootElement.appendChild(this._globalDiv);
  26952. this._generateDOMelements();
  26953. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26954. this._syncPositions();
  26955. this._scene.registerBeforeRender(this._syncData);
  26956. this._scene.registerAfterRender(this._syncUI);
  26957. };
  26958. DebugLayer.prototype._clearLabels = function () {
  26959. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26960. for (var index = 0; index < this._scene.meshes.length; index++) {
  26961. var mesh = this._scene.meshes[index];
  26962. mesh.renderOverlay = false;
  26963. }
  26964. };
  26965. DebugLayer.prototype._generateheader = function (root, text) {
  26966. var header = document.createElement("div");
  26967. header.innerHTML = text + "&nbsp;";
  26968. header.style.textAlign = "right";
  26969. header.style.width = "100%";
  26970. header.style.color = "white";
  26971. header.style.backgroundColor = "Black";
  26972. header.style.padding = "5px 5px 4px 0px";
  26973. header.style.marginLeft = "-5px";
  26974. header.style.fontWeight = "bold";
  26975. root.appendChild(header);
  26976. };
  26977. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26978. var label = document.createElement("label");
  26979. label.innerHTML = title;
  26980. label.style.color = color;
  26981. root.appendChild(label);
  26982. root.appendChild(document.createElement("br"));
  26983. };
  26984. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26985. if (tag === void 0) { tag = null; }
  26986. var label = document.createElement("label");
  26987. var boundingBoxesCheckbox = document.createElement("input");
  26988. boundingBoxesCheckbox.type = "checkbox";
  26989. boundingBoxesCheckbox.checked = initialState;
  26990. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26991. task(evt.target, tag);
  26992. });
  26993. label.appendChild(boundingBoxesCheckbox);
  26994. var container = document.createElement("span");
  26995. var leftPart = document.createElement("span");
  26996. var rightPart = document.createElement("span");
  26997. rightPart.style.cssFloat = "right";
  26998. leftPart.innerHTML = leftTitle;
  26999. rightPart.innerHTML = rightTitle;
  27000. rightPart.style.fontSize = "12px";
  27001. rightPart.style.maxWidth = "200px";
  27002. container.appendChild(leftPart);
  27003. container.appendChild(rightPart);
  27004. label.appendChild(container);
  27005. root.appendChild(label);
  27006. root.appendChild(document.createElement("br"));
  27007. };
  27008. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27009. if (tag === void 0) { tag = null; }
  27010. var label = document.createElement("label");
  27011. var checkBox = document.createElement("input");
  27012. checkBox.type = "checkbox";
  27013. checkBox.checked = initialState;
  27014. checkBox.addEventListener("change", function (evt) {
  27015. task(evt.target, tag);
  27016. });
  27017. label.appendChild(checkBox);
  27018. label.appendChild(document.createTextNode(title));
  27019. root.appendChild(label);
  27020. root.appendChild(document.createElement("br"));
  27021. };
  27022. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27023. if (tag === void 0) { tag = null; }
  27024. var button = document.createElement("button");
  27025. button.innerHTML = title;
  27026. button.style.height = "24px";
  27027. button.style.width = "150px";
  27028. button.style.marginBottom = "5px";
  27029. button.style.color = "#444444";
  27030. button.style.border = "1px solid white";
  27031. button.className = "debugLayerButton";
  27032. button.addEventListener("click", function (evt) {
  27033. task(evt.target, tag);
  27034. });
  27035. root.appendChild(button);
  27036. root.appendChild(document.createElement("br"));
  27037. };
  27038. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27039. if (tag === void 0) { tag = null; }
  27040. var label = document.createElement("label");
  27041. var boundingBoxesRadio = document.createElement("input");
  27042. boundingBoxesRadio.type = "radio";
  27043. boundingBoxesRadio.name = name;
  27044. boundingBoxesRadio.checked = initialState;
  27045. boundingBoxesRadio.addEventListener("change", function (evt) {
  27046. task(evt.target, tag);
  27047. });
  27048. label.appendChild(boundingBoxesRadio);
  27049. label.appendChild(document.createTextNode(title));
  27050. root.appendChild(label);
  27051. root.appendChild(document.createElement("br"));
  27052. };
  27053. DebugLayer.prototype._generateDOMelements = function () {
  27054. var _this = this;
  27055. this._globalDiv.id = "DebugLayer";
  27056. this._globalDiv.style.position = "absolute";
  27057. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27058. this._globalDiv.style.fontSize = "14px";
  27059. this._globalDiv.style.color = "white";
  27060. // Drawing canvas
  27061. this._drawingCanvas = document.createElement("canvas");
  27062. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27063. this._drawingCanvas.style.position = "absolute";
  27064. this._drawingCanvas.style.pointerEvents = "none";
  27065. this._drawingCanvas.style.backgroundColor = "transparent";
  27066. this._drawingContext = this._drawingCanvas.getContext("2d");
  27067. this._globalDiv.appendChild(this._drawingCanvas);
  27068. if (this._showUI) {
  27069. var background = "rgba(128, 128, 128, 0.4)";
  27070. var border = "rgb(180, 180, 180) solid 1px";
  27071. // Stats
  27072. this._statsDiv = document.createElement("div");
  27073. this._statsDiv.id = "DebugLayerStats";
  27074. this._statsDiv.style.border = border;
  27075. this._statsDiv.style.position = "absolute";
  27076. this._statsDiv.style.background = background;
  27077. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27078. this._generateheader(this._statsDiv, "STATISTICS");
  27079. this._statsSubsetDiv = document.createElement("div");
  27080. this._statsSubsetDiv.style.paddingTop = "5px";
  27081. this._statsSubsetDiv.style.paddingBottom = "5px";
  27082. this._statsSubsetDiv.style.overflowY = "auto";
  27083. this._statsDiv.appendChild(this._statsSubsetDiv);
  27084. // Tree
  27085. this._treeDiv = document.createElement("div");
  27086. this._treeDiv.id = "DebugLayerTree";
  27087. this._treeDiv.style.border = border;
  27088. this._treeDiv.style.position = "absolute";
  27089. this._treeDiv.style.background = background;
  27090. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27091. this._treeDiv.style.display = "none";
  27092. this._generateheader(this._treeDiv, "MESHES TREE");
  27093. this._treeSubsetDiv = document.createElement("div");
  27094. this._treeSubsetDiv.style.paddingTop = "5px";
  27095. this._treeSubsetDiv.style.paddingRight = "5px";
  27096. this._treeSubsetDiv.style.overflowY = "auto";
  27097. this._treeSubsetDiv.style.maxHeight = "300px";
  27098. this._treeDiv.appendChild(this._treeSubsetDiv);
  27099. this._needToRefreshMeshesTree = true;
  27100. // Logs
  27101. this._logDiv = document.createElement("div");
  27102. this._logDiv.style.border = border;
  27103. this._logDiv.id = "DebugLayerLogs";
  27104. this._logDiv.style.position = "absolute";
  27105. this._logDiv.style.background = background;
  27106. this._logDiv.style.padding = "0px 0px 0px 5px";
  27107. this._logDiv.style.display = "none";
  27108. this._generateheader(this._logDiv, "LOGS");
  27109. this._logSubsetDiv = document.createElement("div");
  27110. this._logSubsetDiv.style.height = "127px";
  27111. this._logSubsetDiv.style.paddingTop = "5px";
  27112. this._logSubsetDiv.style.overflowY = "auto";
  27113. this._logSubsetDiv.style.fontSize = "12px";
  27114. this._logSubsetDiv.style.fontFamily = "consolas";
  27115. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27116. this._logDiv.appendChild(this._logSubsetDiv);
  27117. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27118. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27119. };
  27120. // Options
  27121. this._optionsDiv = document.createElement("div");
  27122. this._optionsDiv.id = "DebugLayerOptions";
  27123. this._optionsDiv.style.border = border;
  27124. this._optionsDiv.style.position = "absolute";
  27125. this._optionsDiv.style.background = background;
  27126. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27127. this._optionsDiv.style.overflowY = "auto";
  27128. this._generateheader(this._optionsDiv, "OPTIONS");
  27129. this._optionsSubsetDiv = document.createElement("div");
  27130. this._optionsSubsetDiv.style.paddingTop = "5px";
  27131. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27132. this._optionsSubsetDiv.style.overflowY = "auto";
  27133. this._optionsSubsetDiv.style.maxHeight = "200px";
  27134. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27135. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27136. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27137. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27138. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27139. _this._displayTree = element.checked;
  27140. _this._needToRefreshMeshesTree = true;
  27141. });
  27142. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27143. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27144. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27145. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27146. _this._labelsEnabled = element.checked;
  27147. if (!_this._labelsEnabled) {
  27148. _this._clearLabels();
  27149. }
  27150. });
  27151. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27152. if (element.checked) {
  27153. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27154. }
  27155. else {
  27156. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27157. }
  27158. });
  27159. ;
  27160. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27161. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27162. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27163. if (element.checked) {
  27164. _this._scene.forceWireframe = false;
  27165. _this._scene.forcePointsCloud = false;
  27166. }
  27167. });
  27168. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27169. if (element.checked) {
  27170. _this._scene.forceWireframe = true;
  27171. _this._scene.forcePointsCloud = false;
  27172. }
  27173. });
  27174. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27175. if (element.checked) {
  27176. _this._scene.forceWireframe = false;
  27177. _this._scene.forcePointsCloud = true;
  27178. }
  27179. });
  27180. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27181. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27182. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27183. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27184. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27185. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27186. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27187. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27188. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27189. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27190. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27191. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27192. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27193. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27194. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27195. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27196. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27197. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27198. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27199. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27200. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27201. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27202. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27203. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27204. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27205. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27206. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27207. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27208. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27209. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27210. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27211. if (element.checked) {
  27212. _this._scene.headphone = true;
  27213. }
  27214. });
  27215. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27216. if (element.checked) {
  27217. _this._scene.headphone = false;
  27218. }
  27219. });
  27220. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27221. _this._scene.audioEnabled = !element.checked;
  27222. });
  27223. }
  27224. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27225. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27226. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27227. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27228. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27229. this._globalDiv.appendChild(this._statsDiv);
  27230. this._globalDiv.appendChild(this._logDiv);
  27231. this._globalDiv.appendChild(this._optionsDiv);
  27232. this._globalDiv.appendChild(this._treeDiv);
  27233. }
  27234. };
  27235. DebugLayer.prototype._displayStats = function () {
  27236. var scene = this._scene;
  27237. var engine = scene.getEngine();
  27238. var glInfo = engine.getGlInfo();
  27239. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27240. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27241. + "<b>Count</b><br>"
  27242. + "Total meshes: " + scene.meshes.length + "<br>"
  27243. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27244. + "Total materials: " + scene.materials.length + "<br>"
  27245. + "Total textures: " + scene.textures.length + "<br>"
  27246. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27247. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27248. + "Active bones: " + scene.getActiveBones() + "<br>"
  27249. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27250. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27251. + "<b>Duration</b><br>"
  27252. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27253. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27254. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27255. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27256. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27257. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27258. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27259. + "</div>"
  27260. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27261. + "<b>Extensions</b><br>"
  27262. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27263. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27264. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27265. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27266. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27267. + "<b>Caps.</b><br>"
  27268. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27269. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27270. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27271. + "</div><br>"
  27272. + "<b>Info</b><br>"
  27273. + glInfo.version + "<br>"
  27274. + glInfo.renderer + "<br>";
  27275. if (this.customStatsFunction) {
  27276. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27277. }
  27278. };
  27279. return DebugLayer;
  27280. })();
  27281. BABYLON.DebugLayer = DebugLayer;
  27282. })(BABYLON || (BABYLON = {}));
  27283. var BABYLON;
  27284. (function (BABYLON) {
  27285. var DefaultLoadingScreen = (function () {
  27286. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27287. var _this = this;
  27288. if (_loadingText === void 0) { _loadingText = ""; }
  27289. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27290. this._renderingCanvas = _renderingCanvas;
  27291. this._loadingText = _loadingText;
  27292. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27293. // Resize
  27294. this._resizeLoadingUI = function () {
  27295. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27296. _this._loadingDiv.style.position = "absolute";
  27297. _this._loadingDiv.style.left = canvasRect.left + "px";
  27298. _this._loadingDiv.style.top = canvasRect.top + "px";
  27299. _this._loadingDiv.style.width = canvasRect.width + "px";
  27300. _this._loadingDiv.style.height = canvasRect.height + "px";
  27301. };
  27302. }
  27303. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27304. var _this = this;
  27305. this._loadingDiv = document.createElement("div");
  27306. this._loadingDiv.style.opacity = "0";
  27307. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27308. // Loading text
  27309. this._loadingTextDiv = document.createElement("div");
  27310. this._loadingTextDiv.style.position = "absolute";
  27311. this._loadingTextDiv.style.left = "0";
  27312. this._loadingTextDiv.style.top = "50%";
  27313. this._loadingTextDiv.style.marginTop = "80px";
  27314. this._loadingTextDiv.style.width = "100%";
  27315. this._loadingTextDiv.style.height = "20px";
  27316. this._loadingTextDiv.style.fontFamily = "Arial";
  27317. this._loadingTextDiv.style.fontSize = "14px";
  27318. this._loadingTextDiv.style.color = "white";
  27319. this._loadingTextDiv.style.textAlign = "center";
  27320. this._loadingTextDiv.innerHTML = "Loading";
  27321. this._loadingDiv.appendChild(this._loadingTextDiv);
  27322. //set the predefined text
  27323. this._loadingTextDiv.innerHTML = this._loadingText;
  27324. // Loading img
  27325. var imgBack = new Image();
  27326. 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==";
  27327. imgBack.style.position = "absolute";
  27328. imgBack.style.left = "50%";
  27329. imgBack.style.top = "50%";
  27330. imgBack.style.marginLeft = "-50px";
  27331. imgBack.style.marginTop = "-50px";
  27332. imgBack.style.transition = "transform 1.0s ease";
  27333. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27334. var deg = 360;
  27335. var onTransitionEnd = function () {
  27336. deg += 360;
  27337. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27338. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27339. };
  27340. imgBack.addEventListener("transitionend", onTransitionEnd);
  27341. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27342. this._loadingDiv.appendChild(imgBack);
  27343. // front image
  27344. var imgFront = new Image();
  27345. 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=";
  27346. imgFront.style.position = "absolute";
  27347. imgFront.style.left = "50%";
  27348. imgFront.style.top = "50%";
  27349. imgFront.style.marginLeft = "-50px";
  27350. imgFront.style.marginTop = "-50px";
  27351. this._loadingDiv.appendChild(imgFront);
  27352. this._resizeLoadingUI();
  27353. window.addEventListener("resize", this._resizeLoadingUI);
  27354. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27355. document.body.appendChild(this._loadingDiv);
  27356. setTimeout(function () {
  27357. _this._loadingDiv.style.opacity = "1";
  27358. imgBack.style.transform = "rotateZ(360deg)";
  27359. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27360. }, 0);
  27361. };
  27362. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27363. var _this = this;
  27364. if (!this._loadingDiv) {
  27365. return;
  27366. }
  27367. var onTransitionEnd = function () {
  27368. if (!_this._loadingDiv) {
  27369. return;
  27370. }
  27371. document.body.removeChild(_this._loadingDiv);
  27372. window.removeEventListener("resize", _this._resizeLoadingUI);
  27373. _this._loadingDiv = null;
  27374. };
  27375. this._loadingDiv.style.opacity = "0";
  27376. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27377. };
  27378. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27379. set: function (text) {
  27380. this._loadingText = text;
  27381. if (this._loadingTextDiv) {
  27382. this._loadingTextDiv.innerHTML = this._loadingText;
  27383. }
  27384. },
  27385. enumerable: true,
  27386. configurable: true
  27387. });
  27388. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27389. get: function () {
  27390. return this._loadingDivBackgroundColor;
  27391. },
  27392. set: function (color) {
  27393. this._loadingDivBackgroundColor = color;
  27394. if (!this._loadingDiv) {
  27395. return;
  27396. }
  27397. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27398. },
  27399. enumerable: true,
  27400. configurable: true
  27401. });
  27402. return DefaultLoadingScreen;
  27403. })();
  27404. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27405. })(BABYLON || (BABYLON = {}));
  27406. var BABYLON;
  27407. (function (BABYLON) {
  27408. var SIMDVector3 = (function () {
  27409. function SIMDVector3() {
  27410. }
  27411. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27412. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27413. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27414. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27415. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27416. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27417. 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));
  27418. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27419. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27420. };
  27421. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27422. var v0 = SIMD.float32x4.splat(x);
  27423. var v1 = SIMD.float32x4.splat(y);
  27424. var v2 = SIMD.float32x4.splat(z);
  27425. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27426. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27427. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27428. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27429. 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));
  27430. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27431. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27432. };
  27433. return SIMDVector3;
  27434. })();
  27435. BABYLON.SIMDVector3 = SIMDVector3;
  27436. var SIMDMatrix = (function () {
  27437. function SIMDMatrix() {
  27438. }
  27439. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27440. if (offset === void 0) { offset = 0; }
  27441. var tm = this.m;
  27442. var om = other.m;
  27443. var om0 = SIMD.float32x4.load(om, 0);
  27444. var om1 = SIMD.float32x4.load(om, 4);
  27445. var om2 = SIMD.float32x4.load(om, 8);
  27446. var om3 = SIMD.float32x4.load(om, 12);
  27447. var tm0 = SIMD.float32x4.load(tm, 0);
  27448. 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)))));
  27449. var tm1 = SIMD.float32x4.load(tm, 4);
  27450. 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)))));
  27451. var tm2 = SIMD.float32x4.load(tm, 8);
  27452. 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)))));
  27453. var tm3 = SIMD.float32x4.load(tm, 12);
  27454. 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)))));
  27455. };
  27456. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27457. var src = this.m;
  27458. var dest = other.m;
  27459. var row0, row1, row2, row3;
  27460. var tmp1;
  27461. var minor0, minor1, minor2, minor3;
  27462. var det;
  27463. // Load the 4 rows
  27464. var src0 = SIMD.float32x4.load(src, 0);
  27465. var src1 = SIMD.float32x4.load(src, 4);
  27466. var src2 = SIMD.float32x4.load(src, 8);
  27467. var src3 = SIMD.float32x4.load(src, 12);
  27468. // Transpose the source matrix. Sort of. Not a true transpose operation
  27469. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27470. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27471. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27472. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27473. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27474. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27475. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27476. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27477. // This is a true transposition, but it will lead to an incorrect result
  27478. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27479. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27480. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27481. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27482. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27483. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27484. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27485. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27486. // ----
  27487. tmp1 = SIMD.float32x4.mul(row2, row3);
  27488. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27489. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27490. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27491. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27492. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27493. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27494. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27495. // ----
  27496. tmp1 = SIMD.float32x4.mul(row1, row2);
  27497. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27498. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27499. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27500. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27501. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27502. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27503. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27504. // ----
  27505. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27506. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27507. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27508. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27509. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27510. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27511. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27512. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27513. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27514. // ----
  27515. tmp1 = SIMD.float32x4.mul(row0, row1);
  27516. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27517. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27518. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27519. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27520. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27521. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27522. // ----
  27523. tmp1 = SIMD.float32x4.mul(row0, row3);
  27524. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27525. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27526. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27527. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27528. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27529. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27530. // ----
  27531. tmp1 = SIMD.float32x4.mul(row0, row2);
  27532. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27533. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27534. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27535. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27536. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27537. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27538. // Compute determinant
  27539. det = SIMD.float32x4.mul(row0, minor0);
  27540. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27541. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27542. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27543. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27544. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27545. // These shuffles aren't necessary if the faulty transposition is done
  27546. // up at the top of this function.
  27547. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27548. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27549. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27550. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27551. // Compute final values by multiplying with 1/det
  27552. minor0 = SIMD.float32x4.mul(det, minor0);
  27553. minor1 = SIMD.float32x4.mul(det, minor1);
  27554. minor2 = SIMD.float32x4.mul(det, minor2);
  27555. minor3 = SIMD.float32x4.mul(det, minor3);
  27556. SIMD.float32x4.store(dest, 0, minor0);
  27557. SIMD.float32x4.store(dest, 4, minor1);
  27558. SIMD.float32x4.store(dest, 8, minor2);
  27559. SIMD.float32x4.store(dest, 12, minor3);
  27560. return this;
  27561. };
  27562. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27563. var out = result.m;
  27564. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27565. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27566. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27567. // cc.kmVec3Subtract(f, pCenter, pEye);
  27568. var f = SIMD.float32x4.sub(center, eye);
  27569. // cc.kmVec3Normalize(f, f);
  27570. var tmp = SIMD.float32x4.mul(f, f);
  27571. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27572. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27573. // cc.kmVec3Assign(up, pUp);
  27574. // cc.kmVec3Normalize(up, up);
  27575. tmp = SIMD.float32x4.mul(up, up);
  27576. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27577. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27578. // cc.kmVec3Cross(s, f, up);
  27579. 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)));
  27580. // cc.kmVec3Normalize(s, s);
  27581. tmp = SIMD.float32x4.mul(s, s);
  27582. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27583. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27584. // cc.kmVec3Cross(u, s, f);
  27585. 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)));
  27586. // cc.kmVec3Normalize(s, s);
  27587. tmp = SIMD.float32x4.mul(s, s);
  27588. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27589. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27590. var zero = SIMD.float32x4.splat(0.0);
  27591. s = SIMD.float32x4.neg(s);
  27592. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27593. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27594. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27595. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27596. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27597. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27598. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27599. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27600. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27601. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27602. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27603. var b3 = SIMD.float32x4.neg(eye);
  27604. b3 = SIMD.float32x4.withW(b3, 1.0);
  27605. 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)))));
  27606. 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)))));
  27607. 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)))));
  27608. 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)))));
  27609. };
  27610. return SIMDMatrix;
  27611. })();
  27612. BABYLON.SIMDMatrix = SIMDMatrix;
  27613. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27614. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27615. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27616. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27617. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27618. var SIMDHelper = (function () {
  27619. function SIMDHelper() {
  27620. }
  27621. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27622. get: function () {
  27623. return SIMDHelper._isEnabled;
  27624. },
  27625. enumerable: true,
  27626. configurable: true
  27627. });
  27628. SIMDHelper.DisableSIMD = function () {
  27629. // Replace functions
  27630. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27631. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27632. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27633. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27634. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27635. SIMDHelper._isEnabled = false;
  27636. };
  27637. SIMDHelper.EnableSIMD = function () {
  27638. if (window.SIMD === undefined) {
  27639. return;
  27640. }
  27641. // Replace functions
  27642. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27643. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27644. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27645. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27646. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27647. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27648. get: function () { return this._data[0]; },
  27649. set: function (value) {
  27650. if (!this._data) {
  27651. this._data = new Float32Array(3);
  27652. }
  27653. this._data[0] = value;
  27654. }
  27655. });
  27656. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27657. get: function () { return this._data[1]; },
  27658. set: function (value) {
  27659. this._data[1] = value;
  27660. }
  27661. });
  27662. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27663. get: function () { return this._data[2]; },
  27664. set: function (value) {
  27665. this._data[2] = value;
  27666. }
  27667. });
  27668. SIMDHelper._isEnabled = true;
  27669. };
  27670. SIMDHelper._isEnabled = false;
  27671. return SIMDHelper;
  27672. })();
  27673. BABYLON.SIMDHelper = SIMDHelper;
  27674. })(BABYLON || (BABYLON = {}));
  27675. var BABYLON;
  27676. (function (BABYLON) {
  27677. var ShaderMaterial = (function (_super) {
  27678. __extends(ShaderMaterial, _super);
  27679. function ShaderMaterial(name, scene, shaderPath, options) {
  27680. _super.call(this, name, scene);
  27681. this._textures = new Array();
  27682. this._floats = new Array();
  27683. this._floatsArrays = {};
  27684. this._colors3 = new Array();
  27685. this._colors4 = new Array();
  27686. this._vectors2 = new Array();
  27687. this._vectors3 = new Array();
  27688. this._vectors4 = new Array();
  27689. this._matrices = new Array();
  27690. this._matrices3x3 = new Array();
  27691. this._matrices2x2 = new Array();
  27692. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27693. this._shaderPath = shaderPath;
  27694. options.needAlphaBlending = options.needAlphaBlending || false;
  27695. options.needAlphaTesting = options.needAlphaTesting || false;
  27696. options.attributes = options.attributes || ["position", "normal", "uv"];
  27697. options.uniforms = options.uniforms || ["worldViewProjection"];
  27698. options.samplers = options.samplers || [];
  27699. options.defines = options.defines || [];
  27700. this._options = options;
  27701. }
  27702. ShaderMaterial.prototype.needAlphaBlending = function () {
  27703. return this._options.needAlphaBlending;
  27704. };
  27705. ShaderMaterial.prototype.needAlphaTesting = function () {
  27706. return this._options.needAlphaTesting;
  27707. };
  27708. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27709. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27710. this._options.uniforms.push(uniformName);
  27711. }
  27712. };
  27713. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27714. if (this._options.samplers.indexOf(name) === -1) {
  27715. this._options.samplers.push(name);
  27716. }
  27717. this._textures[name] = texture;
  27718. return this;
  27719. };
  27720. ShaderMaterial.prototype.setFloat = function (name, value) {
  27721. this._checkUniform(name);
  27722. this._floats[name] = value;
  27723. return this;
  27724. };
  27725. ShaderMaterial.prototype.setFloats = function (name, value) {
  27726. this._checkUniform(name);
  27727. this._floatsArrays[name] = value;
  27728. return this;
  27729. };
  27730. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27731. this._checkUniform(name);
  27732. this._colors3[name] = value;
  27733. return this;
  27734. };
  27735. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27736. this._checkUniform(name);
  27737. this._colors4[name] = value;
  27738. return this;
  27739. };
  27740. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27741. this._checkUniform(name);
  27742. this._vectors2[name] = value;
  27743. return this;
  27744. };
  27745. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27746. this._checkUniform(name);
  27747. this._vectors3[name] = value;
  27748. return this;
  27749. };
  27750. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27751. this._checkUniform(name);
  27752. this._vectors4[name] = value;
  27753. return this;
  27754. };
  27755. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27756. this._checkUniform(name);
  27757. this._matrices[name] = value;
  27758. return this;
  27759. };
  27760. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27761. this._checkUniform(name);
  27762. this._matrices3x3[name] = value;
  27763. return this;
  27764. };
  27765. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27766. this._checkUniform(name);
  27767. this._matrices2x2[name] = value;
  27768. return this;
  27769. };
  27770. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27771. var scene = this.getScene();
  27772. var engine = scene.getEngine();
  27773. if (!this.checkReadyOnEveryCall) {
  27774. if (this._renderId === scene.getRenderId()) {
  27775. return true;
  27776. }
  27777. }
  27778. // Instances
  27779. var defines = [];
  27780. var fallbacks = new BABYLON.EffectFallbacks();
  27781. if (useInstances) {
  27782. defines.push("#define INSTANCES");
  27783. }
  27784. for (var index = 0; index < this._options.defines.length; index++) {
  27785. defines.push(this._options.defines[index]);
  27786. }
  27787. // Bones
  27788. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27789. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  27790. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27791. fallbacks.addCPUSkinningFallback(0, mesh);
  27792. }
  27793. // Alpha test
  27794. if (engine.getAlphaTesting()) {
  27795. defines.push("#define ALPHATEST");
  27796. }
  27797. var previousEffect = this._effect;
  27798. var join = defines.join("\n");
  27799. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27800. if (!this._effect.isReady()) {
  27801. return false;
  27802. }
  27803. if (previousEffect !== this._effect) {
  27804. scene.resetCachedMaterial();
  27805. }
  27806. this._renderId = scene.getRenderId();
  27807. return true;
  27808. };
  27809. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27810. var scene = this.getScene();
  27811. if (this._options.uniforms.indexOf("world") !== -1) {
  27812. this._effect.setMatrix("world", world);
  27813. }
  27814. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27815. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27816. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27817. }
  27818. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27819. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27820. }
  27821. };
  27822. ShaderMaterial.prototype.bind = function (world, mesh) {
  27823. // Std values
  27824. this.bindOnlyWorldMatrix(world);
  27825. if (this.getScene().getCachedMaterial() !== this) {
  27826. if (this._options.uniforms.indexOf("view") !== -1) {
  27827. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27828. }
  27829. if (this._options.uniforms.indexOf("projection") !== -1) {
  27830. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27831. }
  27832. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27833. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27834. }
  27835. // Bones
  27836. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27837. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27838. }
  27839. // Texture
  27840. for (var name in this._textures) {
  27841. this._effect.setTexture(name, this._textures[name]);
  27842. }
  27843. // Float
  27844. for (name in this._floats) {
  27845. this._effect.setFloat(name, this._floats[name]);
  27846. }
  27847. // Float s
  27848. for (name in this._floatsArrays) {
  27849. this._effect.setArray(name, this._floatsArrays[name]);
  27850. }
  27851. // Color3
  27852. for (name in this._colors3) {
  27853. this._effect.setColor3(name, this._colors3[name]);
  27854. }
  27855. // Color4
  27856. for (name in this._colors4) {
  27857. var color = this._colors4[name];
  27858. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27859. }
  27860. // Vector2
  27861. for (name in this._vectors2) {
  27862. this._effect.setVector2(name, this._vectors2[name]);
  27863. }
  27864. // Vector3
  27865. for (name in this._vectors3) {
  27866. this._effect.setVector3(name, this._vectors3[name]);
  27867. }
  27868. // Vector4
  27869. for (name in this._vectors4) {
  27870. this._effect.setVector4(name, this._vectors4[name]);
  27871. }
  27872. // Matrix
  27873. for (name in this._matrices) {
  27874. this._effect.setMatrix(name, this._matrices[name]);
  27875. }
  27876. // Matrix 3x3
  27877. for (name in this._matrices3x3) {
  27878. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27879. }
  27880. // Matrix 2x2
  27881. for (name in this._matrices2x2) {
  27882. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27883. }
  27884. }
  27885. _super.prototype.bind.call(this, world, mesh);
  27886. };
  27887. ShaderMaterial.prototype.clone = function (name) {
  27888. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27889. return newShaderMaterial;
  27890. };
  27891. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27892. for (var name in this._textures) {
  27893. this._textures[name].dispose();
  27894. }
  27895. this._textures = [];
  27896. _super.prototype.dispose.call(this, forceDisposeEffect);
  27897. };
  27898. return ShaderMaterial;
  27899. })(BABYLON.Material);
  27900. BABYLON.ShaderMaterial = ShaderMaterial;
  27901. })(BABYLON || (BABYLON = {}));
  27902. var BABYLON;
  27903. (function (BABYLON) {
  27904. var Internals;
  27905. (function (Internals) {
  27906. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27907. // All values and structures referenced from:
  27908. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27909. var DDS_MAGIC = 0x20534444;
  27910. 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;
  27911. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27912. 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;
  27913. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27914. function FourCCToInt32(value) {
  27915. return value.charCodeAt(0) +
  27916. (value.charCodeAt(1) << 8) +
  27917. (value.charCodeAt(2) << 16) +
  27918. (value.charCodeAt(3) << 24);
  27919. }
  27920. function Int32ToFourCC(value) {
  27921. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27922. }
  27923. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27924. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27925. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27926. var headerLengthInt = 31; // The header length in 32 bit ints
  27927. // Offsets into the header array
  27928. var off_magic = 0;
  27929. var off_size = 1;
  27930. var off_flags = 2;
  27931. var off_height = 3;
  27932. var off_width = 4;
  27933. var off_mipmapCount = 7;
  27934. var off_pfFlags = 20;
  27935. var off_pfFourCC = 21;
  27936. var off_RGBbpp = 22;
  27937. var off_RMask = 23;
  27938. var off_GMask = 24;
  27939. var off_BMask = 25;
  27940. var off_AMask = 26;
  27941. var off_caps1 = 27;
  27942. var off_caps2 = 28;
  27943. ;
  27944. var DDSTools = (function () {
  27945. function DDSTools() {
  27946. }
  27947. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27948. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27949. var mipmapCount = 1;
  27950. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27951. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27952. }
  27953. return {
  27954. width: header[off_width],
  27955. height: header[off_height],
  27956. mipmapCount: mipmapCount,
  27957. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27958. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27959. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27960. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27961. };
  27962. };
  27963. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27964. var byteArray = new Uint8Array(dataLength);
  27965. var srcData = new Uint8Array(arrayBuffer);
  27966. var index = 0;
  27967. for (var y = height - 1; y >= 0; y--) {
  27968. for (var x = 0; x < width; x++) {
  27969. var srcPos = dataOffset + (x + y * width) * 4;
  27970. byteArray[index + 2] = srcData[srcPos];
  27971. byteArray[index + 1] = srcData[srcPos + 1];
  27972. byteArray[index] = srcData[srcPos + 2];
  27973. byteArray[index + 3] = srcData[srcPos + 3];
  27974. index += 4;
  27975. }
  27976. }
  27977. return byteArray;
  27978. };
  27979. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27980. var byteArray = new Uint8Array(dataLength);
  27981. var srcData = new Uint8Array(arrayBuffer);
  27982. var index = 0;
  27983. for (var y = height - 1; y >= 0; y--) {
  27984. for (var x = 0; x < width; x++) {
  27985. var srcPos = dataOffset + (x + y * width) * 3;
  27986. byteArray[index + 2] = srcData[srcPos];
  27987. byteArray[index + 1] = srcData[srcPos + 1];
  27988. byteArray[index] = srcData[srcPos + 2];
  27989. index += 3;
  27990. }
  27991. }
  27992. return byteArray;
  27993. };
  27994. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27995. var byteArray = new Uint8Array(dataLength);
  27996. var srcData = new Uint8Array(arrayBuffer);
  27997. var index = 0;
  27998. for (var y = height - 1; y >= 0; y--) {
  27999. for (var x = 0; x < width; x++) {
  28000. var srcPos = dataOffset + (x + y * width);
  28001. byteArray[index] = srcData[srcPos];
  28002. index++;
  28003. }
  28004. }
  28005. return byteArray;
  28006. };
  28007. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28008. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28009. if (header[off_magic] != DDS_MAGIC) {
  28010. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28011. return;
  28012. }
  28013. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28014. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28015. return;
  28016. }
  28017. if (info.isFourCC) {
  28018. fourCC = header[off_pfFourCC];
  28019. switch (fourCC) {
  28020. case FOURCC_DXT1:
  28021. blockBytes = 8;
  28022. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28023. break;
  28024. case FOURCC_DXT3:
  28025. blockBytes = 16;
  28026. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28027. break;
  28028. case FOURCC_DXT5:
  28029. blockBytes = 16;
  28030. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28031. break;
  28032. default:
  28033. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28034. return;
  28035. }
  28036. }
  28037. mipmapCount = 1;
  28038. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28039. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28040. }
  28041. var bpp = header[off_RGBbpp];
  28042. for (var face = 0; face < faces; face++) {
  28043. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28044. width = header[off_width];
  28045. height = header[off_height];
  28046. dataOffset = header[off_size] + 4;
  28047. for (i = 0; i < mipmapCount; ++i) {
  28048. if (info.isRGB) {
  28049. if (bpp === 24) {
  28050. dataLength = width * height * 3;
  28051. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28052. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28053. }
  28054. else {
  28055. dataLength = width * height * 4;
  28056. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28057. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28058. }
  28059. }
  28060. else if (info.isLuminance) {
  28061. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28062. var unpaddedRowSize = width;
  28063. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28064. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28065. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28066. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28067. }
  28068. else {
  28069. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28070. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28071. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28072. }
  28073. dataOffset += dataLength;
  28074. width *= 0.5;
  28075. height *= 0.5;
  28076. width = Math.max(1.0, width);
  28077. height = Math.max(1.0, height);
  28078. }
  28079. }
  28080. };
  28081. return DDSTools;
  28082. })();
  28083. Internals.DDSTools = DDSTools;
  28084. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28085. })(BABYLON || (BABYLON = {}));
  28086. var BABYLON;
  28087. (function (BABYLON) {
  28088. var CannonJSPlugin = (function () {
  28089. function CannonJSPlugin() {
  28090. this._registeredMeshes = [];
  28091. this._physicsMaterials = [];
  28092. this.updateBodyPosition = function (mesh) {
  28093. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28094. var registeredMesh = this._registeredMeshes[index];
  28095. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28096. var body = registeredMesh.body;
  28097. var center = mesh.getBoundingInfo().boundingBox.center;
  28098. body.position.set(center.x, center.y, center.z);
  28099. body.quaternion.copy(mesh.rotationQuaternion);
  28100. if (registeredMesh.deltaRotation) {
  28101. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28102. body.quaternion = body.quaternion.mult(tmpQ);
  28103. }
  28104. if (registeredMesh.heightmap) {
  28105. //calculate the correct body position:
  28106. var rotationQuaternion = mesh.rotationQuaternion;
  28107. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28108. mesh.computeWorldMatrix(true);
  28109. //get original center with no rotation
  28110. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28111. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28112. //rotation is back
  28113. mesh.rotationQuaternion = rotationQuaternion;
  28114. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28115. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28116. mesh.setPivotMatrix(p);
  28117. mesh.computeWorldMatrix(true);
  28118. //calculate the translation
  28119. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28120. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28121. //add it inverted to the delta
  28122. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28123. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28124. mesh.setPivotMatrix(oldPivot);
  28125. mesh.computeWorldMatrix(true);
  28126. }
  28127. return;
  28128. }
  28129. }
  28130. };
  28131. }
  28132. CannonJSPlugin.prototype.initialize = function (iterations) {
  28133. if (iterations === void 0) { iterations = 10; }
  28134. this._world = new CANNON.World();
  28135. this._world.broadphase = new CANNON.NaiveBroadphase();
  28136. this._world.solver.iterations = iterations;
  28137. };
  28138. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28139. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28140. };
  28141. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28142. var _this = this;
  28143. this._world.step(delta);
  28144. this._registeredMeshes.forEach(function (registeredMesh) {
  28145. // Body position
  28146. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28147. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28148. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28149. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28150. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28151. if (registeredMesh.deltaRotation) {
  28152. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28153. }
  28154. //is the physics collision callback is set?
  28155. if (registeredMesh.mesh.onPhysicsCollide) {
  28156. if (!registeredMesh.collisionFunction) {
  28157. registeredMesh.collisionFunction = function (e) {
  28158. //find the mesh that collided with the registered mesh
  28159. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28160. if (_this._registeredMeshes[idx].body == e.body) {
  28161. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28162. }
  28163. }
  28164. };
  28165. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28166. }
  28167. }
  28168. else {
  28169. //unregister, in case the function was removed for some reason
  28170. if (registeredMesh.collisionFunction) {
  28171. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28172. }
  28173. }
  28174. });
  28175. };
  28176. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28177. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28178. };
  28179. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28180. this.unregisterMesh(mesh);
  28181. if (!mesh.rotationQuaternion) {
  28182. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28183. }
  28184. mesh.computeWorldMatrix(true);
  28185. var shape = this._createShape(mesh, impostor);
  28186. return this._createRigidBodyFromShape(shape, mesh, options);
  28187. };
  28188. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28189. //get the correct bounding box
  28190. var oldQuaternion = mesh.rotationQuaternion;
  28191. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28192. mesh.computeWorldMatrix(true);
  28193. var returnValue;
  28194. switch (impostor) {
  28195. case BABYLON.PhysicsEngine.SphereImpostor:
  28196. var bbox = mesh.getBoundingInfo().boundingBox;
  28197. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28198. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28199. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28200. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28201. break;
  28202. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28203. case BABYLON.PhysicsEngine.CylinderImpostor:
  28204. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28205. case BABYLON.PhysicsEngine.BoxImpostor:
  28206. bbox = mesh.getBoundingInfo().boundingBox;
  28207. var min = bbox.minimumWorld;
  28208. var max = bbox.maximumWorld;
  28209. var box = max.subtract(min).scale(0.5);
  28210. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28211. break;
  28212. case BABYLON.PhysicsEngine.PlaneImpostor:
  28213. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28214. returnValue = new CANNON.Plane();
  28215. break;
  28216. case BABYLON.PhysicsEngine.MeshImpostor:
  28217. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28218. var rawFaces = mesh.getIndices();
  28219. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28220. break;
  28221. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28222. returnValue = this._createHeightmap(mesh);
  28223. break;
  28224. }
  28225. mesh.rotationQuaternion = oldQuaternion;
  28226. return returnValue;
  28227. };
  28228. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28229. var verts = [], faces = [];
  28230. mesh.computeWorldMatrix(true);
  28231. //reuse this variable
  28232. var transformed = BABYLON.Vector3.Zero();
  28233. // Get vertices
  28234. for (var i = 0; i < rawVerts.length; i += 3) {
  28235. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28236. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28237. }
  28238. // Get faces
  28239. for (var j = 0; j < rawFaces.length; j += 3) {
  28240. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28241. }
  28242. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28243. return shape;
  28244. };
  28245. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28246. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28247. var matrix = [];
  28248. //For now pointDepth will not be used and will be automatically calculated.
  28249. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28250. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28251. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28252. var elementSize = dim * 2 / arraySize;
  28253. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28254. for (var i = 0; i < pos.length; i = i + 3) {
  28255. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28256. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28257. var y = pos[i + 1] + minY;
  28258. if (!matrix[x]) {
  28259. matrix[x] = [];
  28260. }
  28261. if (!matrix[x][z]) {
  28262. matrix[x][z] = y;
  28263. }
  28264. matrix[x][z] = Math.max(y, matrix[x][z]);
  28265. }
  28266. for (var x = 0; x <= arraySize; ++x) {
  28267. if (!matrix[x]) {
  28268. var loc = 1;
  28269. while (!matrix[(x + loc) % arraySize]) {
  28270. loc++;
  28271. }
  28272. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28273. }
  28274. for (var z = 0; z <= arraySize; ++z) {
  28275. if (!matrix[x][z]) {
  28276. var loc = 1;
  28277. var newValue;
  28278. while (newValue === undefined) {
  28279. newValue = matrix[x][(z + loc++) % arraySize];
  28280. }
  28281. matrix[x][z] = newValue;
  28282. }
  28283. }
  28284. }
  28285. var shape = new CANNON.Heightfield(matrix, {
  28286. elementSize: elementSize
  28287. });
  28288. //For future reference, needed for body transformation
  28289. shape.minY = minY;
  28290. return shape;
  28291. };
  28292. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28293. var index;
  28294. var mat;
  28295. for (index = 0; index < this._physicsMaterials.length; index++) {
  28296. mat = this._physicsMaterials[index];
  28297. if (mat.friction === friction && mat.restitution === restitution) {
  28298. return mat;
  28299. }
  28300. }
  28301. var currentMat = new CANNON.Material("mat");
  28302. this._physicsMaterials.push(currentMat);
  28303. for (index = 0; index < this._physicsMaterials.length; index++) {
  28304. mat = this._physicsMaterials[index];
  28305. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28306. this._world.addContactMaterial(contactMaterial);
  28307. }
  28308. return currentMat;
  28309. };
  28310. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28311. if (!mesh.rotationQuaternion) {
  28312. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28313. }
  28314. // The delta between the mesh position and the mesh bounding box center
  28315. var bbox = mesh.getBoundingInfo().boundingBox;
  28316. var deltaPosition = mesh.position.subtract(bbox.center);
  28317. var deltaRotation;
  28318. var material = this._addMaterial(options.friction, options.restitution);
  28319. var body = new CANNON.Body({
  28320. mass: options.mass,
  28321. material: material,
  28322. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28323. });
  28324. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28325. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28326. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28327. //-90 DEG in X, precalculated
  28328. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28329. body.quaternion = body.quaternion.mult(tmpQ);
  28330. //Invert! (Precalculated, 90 deg in X)
  28331. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28332. }
  28333. //If it is a heightfield, if should be centered.
  28334. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28335. //calculate the correct body position:
  28336. var rotationQuaternion = mesh.rotationQuaternion;
  28337. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28338. mesh.computeWorldMatrix(true);
  28339. //get original center with no rotation
  28340. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28341. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28342. //rotation is back
  28343. mesh.rotationQuaternion = rotationQuaternion;
  28344. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28345. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28346. mesh.setPivotMatrix(p);
  28347. mesh.computeWorldMatrix(true);
  28348. //calculate the translation
  28349. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28350. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28351. //add it inverted to the delta
  28352. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28353. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28354. mesh.setPivotMatrix(oldPivot);
  28355. mesh.computeWorldMatrix(true);
  28356. }
  28357. //add the shape
  28358. body.addShape(shape);
  28359. this._world.add(body);
  28360. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28361. return body;
  28362. };
  28363. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28364. var initialMesh = parts[0].mesh;
  28365. this.unregisterMesh(initialMesh);
  28366. initialMesh.computeWorldMatrix(true);
  28367. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28368. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28369. for (var index = 1; index < parts.length; index++) {
  28370. var mesh = parts[index].mesh;
  28371. mesh.computeWorldMatrix(true);
  28372. var shape = this._createShape(mesh, parts[index].impostor);
  28373. var localPosition = mesh.position;
  28374. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28375. }
  28376. return body;
  28377. };
  28378. CannonJSPlugin.prototype._unbindBody = function (body) {
  28379. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28380. var registeredMesh = this._registeredMeshes[index];
  28381. if (registeredMesh.body === body) {
  28382. this._world.remove(registeredMesh.body);
  28383. registeredMesh.body = null;
  28384. registeredMesh.delta = null;
  28385. registeredMesh.deltaRotation = null;
  28386. }
  28387. }
  28388. };
  28389. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28390. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28391. var registeredMesh = this._registeredMeshes[index];
  28392. if (registeredMesh.mesh === mesh) {
  28393. // Remove body
  28394. if (registeredMesh.body) {
  28395. this._unbindBody(registeredMesh.body);
  28396. }
  28397. this._registeredMeshes.splice(index, 1);
  28398. return;
  28399. }
  28400. }
  28401. };
  28402. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28403. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28404. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28405. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28406. var registeredMesh = this._registeredMeshes[index];
  28407. if (registeredMesh.mesh === mesh) {
  28408. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28409. return;
  28410. }
  28411. }
  28412. };
  28413. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28414. var body1 = null, body2 = null;
  28415. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28416. var registeredMesh = this._registeredMeshes[index];
  28417. if (registeredMesh.mesh === mesh1) {
  28418. body1 = registeredMesh.body;
  28419. }
  28420. else if (registeredMesh.mesh === mesh2) {
  28421. body2 = registeredMesh.body;
  28422. }
  28423. }
  28424. if (!body1 || !body2) {
  28425. return false;
  28426. }
  28427. 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));
  28428. this._world.addConstraint(constraint);
  28429. return true;
  28430. };
  28431. CannonJSPlugin.prototype.dispose = function () {
  28432. while (this._registeredMeshes.length) {
  28433. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28434. }
  28435. };
  28436. CannonJSPlugin.prototype.isSupported = function () {
  28437. return window.CANNON !== undefined;
  28438. };
  28439. CannonJSPlugin.prototype.getWorldObject = function () {
  28440. return this._world;
  28441. };
  28442. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28443. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28444. var registeredMesh = this._registeredMeshes[index];
  28445. if (registeredMesh.mesh === mesh) {
  28446. return registeredMesh.body;
  28447. }
  28448. }
  28449. return null;
  28450. };
  28451. return CannonJSPlugin;
  28452. })();
  28453. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28454. })(BABYLON || (BABYLON = {}));
  28455. var BABYLON;
  28456. (function (BABYLON) {
  28457. var OimoJSPlugin = (function () {
  28458. function OimoJSPlugin() {
  28459. this._registeredMeshes = [];
  28460. /**
  28461. * Update the body position according to the mesh position
  28462. * @param mesh
  28463. */
  28464. this.updateBodyPosition = function (mesh) {
  28465. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28466. var registeredMesh = this._registeredMeshes[index];
  28467. var body = registeredMesh.body.body;
  28468. var updated = false;
  28469. var newPosition;
  28470. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28471. mesh.computeWorldMatrix(true);
  28472. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28473. updated = true;
  28474. }
  28475. else if (registeredMesh.mesh.parent === mesh) {
  28476. mesh.computeWorldMatrix(true);
  28477. registeredMesh.mesh.computeWorldMatrix(true);
  28478. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28479. updated = true;
  28480. }
  28481. if (updated) {
  28482. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28483. body.setQuaternion(mesh.rotationQuaternion);
  28484. body.sleeping = false;
  28485. //force Oimo to update the body's position
  28486. body.updatePosition(1);
  28487. }
  28488. }
  28489. };
  28490. }
  28491. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28492. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28493. };
  28494. OimoJSPlugin.prototype.initialize = function (iterations) {
  28495. this._world = new OIMO.World(null, null, iterations);
  28496. this._world.clear();
  28497. };
  28498. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28499. this._world.gravity = gravity;
  28500. };
  28501. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28502. this.unregisterMesh(mesh);
  28503. if (!mesh.rotationQuaternion) {
  28504. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28505. }
  28506. mesh.computeWorldMatrix(true);
  28507. var bbox = mesh.getBoundingInfo().boundingBox;
  28508. // The delta between the mesh position and the mesh bounding box center
  28509. var deltaPosition = mesh.position.subtract(bbox.center);
  28510. //calculate rotation to fit Oimo's needs (Euler...)
  28511. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28512. //get the correct bounding box
  28513. var oldQuaternion = mesh.rotationQuaternion;
  28514. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28515. mesh.computeWorldMatrix(true);
  28516. var bodyConfig = {
  28517. name: mesh.uniqueId,
  28518. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28519. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28520. move: options.mass != 0,
  28521. config: [options.mass, options.friction, options.restitution],
  28522. world: this._world
  28523. };
  28524. // register mesh
  28525. switch (impostor) {
  28526. case BABYLON.PhysicsEngine.SphereImpostor:
  28527. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28528. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28529. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28530. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28531. bodyConfig.type = 'sphere';
  28532. bodyConfig.size = [size];
  28533. break;
  28534. case BABYLON.PhysicsEngine.PlaneImpostor:
  28535. //Oimo "fakes" a cylinder as a box, so why don't we!
  28536. case BABYLON.PhysicsEngine.CylinderImpostor:
  28537. case BABYLON.PhysicsEngine.BoxImpostor:
  28538. var min = bbox.minimumWorld;
  28539. var max = bbox.maximumWorld;
  28540. var box = max.subtract(min);
  28541. var sizeX = this._checkWithEpsilon(box.x);
  28542. var sizeY = this._checkWithEpsilon(box.y);
  28543. var sizeZ = this._checkWithEpsilon(box.z);
  28544. bodyConfig.type = 'box';
  28545. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28546. break;
  28547. }
  28548. var body = new OIMO.Body(bodyConfig);
  28549. //We have to access the rigid body's properties to set the quaternion.
  28550. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28551. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28552. //TEST
  28553. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28554. //update the internal rotation matrix
  28555. //body.body.syncShapes();
  28556. this._registeredMeshes.push({
  28557. mesh: mesh,
  28558. body: body,
  28559. delta: deltaPosition
  28560. });
  28561. //for the sake of consistency.
  28562. mesh.rotationQuaternion = oldQuaternion;
  28563. return body;
  28564. };
  28565. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28566. var types = [], sizes = [], positions = [], rotations = [];
  28567. var initialMesh = parts[0].mesh;
  28568. for (var index = 0; index < parts.length; index++) {
  28569. var part = parts[index];
  28570. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28571. types.push(bodyParameters.type);
  28572. sizes.push.apply(sizes, bodyParameters.size);
  28573. positions.push.apply(positions, bodyParameters.pos);
  28574. rotations.push.apply(rotations, bodyParameters.rot);
  28575. }
  28576. var body = new OIMO.Body({
  28577. name: initialMesh.uniqueId,
  28578. type: types,
  28579. size: sizes,
  28580. pos: positions,
  28581. rot: rotations,
  28582. move: options.mass != 0,
  28583. config: [options.mass, options.friction, options.restitution],
  28584. world: this._world
  28585. });
  28586. //Reset the body's rotation to be of the initial mesh's.
  28587. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28588. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28589. this._registeredMeshes.push({
  28590. mesh: initialMesh,
  28591. body: body
  28592. });
  28593. return body;
  28594. };
  28595. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28596. var mesh = part.mesh;
  28597. if (!mesh.rotationQuaternion) {
  28598. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28599. }
  28600. // We need the bounding box/sphere info to compute the physics body
  28601. mesh.computeWorldMatrix(true);
  28602. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28603. var bodyParameters = {
  28604. name: mesh.uniqueId,
  28605. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28606. //A bug in Oimo (Body class) prevents us from using rot directly.
  28607. rot: [0, 0, 0],
  28608. //For future reference, if the bug will ever be fixed.
  28609. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28610. };
  28611. var oldQuaternion = mesh.rotationQuaternion;
  28612. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28613. mesh.computeWorldMatrix(true);
  28614. switch (part.impostor) {
  28615. case BABYLON.PhysicsEngine.SphereImpostor:
  28616. var bbox = mesh.getBoundingInfo().boundingBox;
  28617. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28618. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28619. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28620. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28621. bodyParameters.type = 'sphere';
  28622. bodyParameters.size = [size, size, size];
  28623. break;
  28624. case BABYLON.PhysicsEngine.PlaneImpostor:
  28625. case BABYLON.PhysicsEngine.CylinderImpostor:
  28626. case BABYLON.PhysicsEngine.BoxImpostor:
  28627. bbox = mesh.getBoundingInfo().boundingBox;
  28628. var min = bbox.minimumWorld;
  28629. var max = bbox.maximumWorld;
  28630. var box = max.subtract(min);
  28631. var sizeX = this._checkWithEpsilon(box.x);
  28632. var sizeY = this._checkWithEpsilon(box.y);
  28633. var sizeZ = this._checkWithEpsilon(box.z);
  28634. bodyParameters.type = 'box';
  28635. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28636. break;
  28637. }
  28638. mesh.rotationQuaternion = oldQuaternion;
  28639. return bodyParameters;
  28640. };
  28641. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28642. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28643. var registeredMesh = this._registeredMeshes[index];
  28644. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28645. if (registeredMesh.body) {
  28646. this._world.removeRigidBody(registeredMesh.body.body);
  28647. this._unbindBody(registeredMesh.body);
  28648. }
  28649. this._registeredMeshes.splice(index, 1);
  28650. return;
  28651. }
  28652. }
  28653. };
  28654. OimoJSPlugin.prototype._unbindBody = function (body) {
  28655. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28656. var registeredMesh = this._registeredMeshes[index];
  28657. if (registeredMesh.body === body) {
  28658. registeredMesh.body = null;
  28659. }
  28660. }
  28661. };
  28662. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28663. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28664. var registeredMesh = this._registeredMeshes[index];
  28665. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28666. // Get object mass to have a behaviour similar to cannon.js
  28667. var mass = registeredMesh.body.body.massInfo.mass;
  28668. // The force is scaled with the mass of object
  28669. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28670. return;
  28671. }
  28672. }
  28673. };
  28674. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28675. var body1 = null, body2 = null;
  28676. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28677. var registeredMesh = this._registeredMeshes[index];
  28678. if (registeredMesh.mesh === mesh1) {
  28679. body1 = registeredMesh.body.body;
  28680. }
  28681. else if (registeredMesh.mesh === mesh2) {
  28682. body2 = registeredMesh.body.body;
  28683. }
  28684. }
  28685. if (!body1 || !body2) {
  28686. return false;
  28687. }
  28688. if (!options) {
  28689. options = {};
  28690. }
  28691. new OIMO.Link({
  28692. type: options.type,
  28693. body1: body1,
  28694. body2: body2,
  28695. min: options.min,
  28696. max: options.max,
  28697. axe1: options.axe1,
  28698. axe2: options.axe2,
  28699. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28700. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28701. collision: options.collision,
  28702. spring: options.spring,
  28703. world: this._world
  28704. });
  28705. return true;
  28706. };
  28707. OimoJSPlugin.prototype.dispose = function () {
  28708. this._world.clear();
  28709. while (this._registeredMeshes.length) {
  28710. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28711. }
  28712. };
  28713. OimoJSPlugin.prototype.isSupported = function () {
  28714. return OIMO !== undefined;
  28715. };
  28716. OimoJSPlugin.prototype.getWorldObject = function () {
  28717. return this._world;
  28718. };
  28719. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28720. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28721. var registeredMesh = this._registeredMeshes[index];
  28722. if (registeredMesh.mesh === mesh) {
  28723. return registeredMesh.body;
  28724. }
  28725. }
  28726. return null;
  28727. };
  28728. OimoJSPlugin.prototype._getLastShape = function (body) {
  28729. var lastShape = body.shapes;
  28730. while (lastShape.next) {
  28731. lastShape = lastShape.next;
  28732. }
  28733. return lastShape;
  28734. };
  28735. OimoJSPlugin.prototype.runOneStep = function (time) {
  28736. this._world.step();
  28737. // Update the position of all registered meshes
  28738. var i = this._registeredMeshes.length;
  28739. var m;
  28740. while (i--) {
  28741. var body = this._registeredMeshes[i].body.body;
  28742. var mesh = this._registeredMeshes[i].mesh;
  28743. if (!this._registeredMeshes[i].delta) {
  28744. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28745. }
  28746. if (!body.sleeping) {
  28747. //TODO check that
  28748. if (body.shapes.next) {
  28749. var parentShape = this._getLastShape(body);
  28750. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28751. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28752. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28753. }
  28754. else {
  28755. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28756. }
  28757. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28758. mesh.computeWorldMatrix();
  28759. }
  28760. //check if the collide callback is set.
  28761. if (mesh.onPhysicsCollide) {
  28762. var meshUniqueName = mesh.uniqueId;
  28763. var contact = this._world.contacts;
  28764. while (contact !== null) {
  28765. //is this body colliding with any other?
  28766. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  28767. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  28768. //get the mesh and execute the callback
  28769. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  28770. if (otherMesh)
  28771. mesh.onPhysicsCollide(otherMesh);
  28772. }
  28773. contact = contact.next;
  28774. }
  28775. }
  28776. }
  28777. };
  28778. return OimoJSPlugin;
  28779. })();
  28780. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28781. })(BABYLON || (BABYLON = {}));
  28782. var BABYLON;
  28783. (function (BABYLON) {
  28784. var DisplayPassPostProcess = (function (_super) {
  28785. __extends(DisplayPassPostProcess, _super);
  28786. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28787. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28788. }
  28789. return DisplayPassPostProcess;
  28790. })(BABYLON.PostProcess);
  28791. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28792. })(BABYLON || (BABYLON = {}));
  28793. var BABYLON;
  28794. (function (BABYLON) {
  28795. var SimplificationSettings = (function () {
  28796. function SimplificationSettings(quality, distance, optimizeMesh) {
  28797. this.quality = quality;
  28798. this.distance = distance;
  28799. this.optimizeMesh = optimizeMesh;
  28800. }
  28801. return SimplificationSettings;
  28802. })();
  28803. BABYLON.SimplificationSettings = SimplificationSettings;
  28804. var SimplificationQueue = (function () {
  28805. function SimplificationQueue() {
  28806. this.running = false;
  28807. this._simplificationArray = [];
  28808. }
  28809. SimplificationQueue.prototype.addTask = function (task) {
  28810. this._simplificationArray.push(task);
  28811. };
  28812. SimplificationQueue.prototype.executeNext = function () {
  28813. var task = this._simplificationArray.pop();
  28814. if (task) {
  28815. this.running = true;
  28816. this.runSimplification(task);
  28817. }
  28818. else {
  28819. this.running = false;
  28820. }
  28821. };
  28822. SimplificationQueue.prototype.runSimplification = function (task) {
  28823. var _this = this;
  28824. if (task.parallelProcessing) {
  28825. //parallel simplifier
  28826. task.settings.forEach(function (setting) {
  28827. var simplifier = _this.getSimplifier(task);
  28828. simplifier.simplify(setting, function (newMesh) {
  28829. task.mesh.addLODLevel(setting.distance, newMesh);
  28830. newMesh.isVisible = true;
  28831. //check if it is the last
  28832. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28833. //all done, run the success callback.
  28834. task.successCallback();
  28835. }
  28836. _this.executeNext();
  28837. });
  28838. });
  28839. }
  28840. else {
  28841. //single simplifier.
  28842. var simplifier = this.getSimplifier(task);
  28843. var runDecimation = function (setting, callback) {
  28844. simplifier.simplify(setting, function (newMesh) {
  28845. task.mesh.addLODLevel(setting.distance, newMesh);
  28846. newMesh.isVisible = true;
  28847. //run the next quality level
  28848. callback();
  28849. });
  28850. };
  28851. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28852. runDecimation(task.settings[loop.index], function () {
  28853. loop.executeNext();
  28854. });
  28855. }, function () {
  28856. //execution ended, run the success callback.
  28857. if (task.successCallback) {
  28858. task.successCallback();
  28859. }
  28860. _this.executeNext();
  28861. });
  28862. }
  28863. };
  28864. SimplificationQueue.prototype.getSimplifier = function (task) {
  28865. switch (task.simplificationType) {
  28866. case SimplificationType.QUADRATIC:
  28867. default:
  28868. return new QuadraticErrorSimplification(task.mesh);
  28869. }
  28870. };
  28871. return SimplificationQueue;
  28872. })();
  28873. BABYLON.SimplificationQueue = SimplificationQueue;
  28874. /**
  28875. * The implemented types of simplification.
  28876. * At the moment only Quadratic Error Decimation is implemented.
  28877. */
  28878. (function (SimplificationType) {
  28879. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28880. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28881. var SimplificationType = BABYLON.SimplificationType;
  28882. var DecimationTriangle = (function () {
  28883. function DecimationTriangle(vertices) {
  28884. this.vertices = vertices;
  28885. this.error = new Array(4);
  28886. this.deleted = false;
  28887. this.isDirty = false;
  28888. this.deletePending = false;
  28889. this.borderFactor = 0;
  28890. }
  28891. return DecimationTriangle;
  28892. })();
  28893. BABYLON.DecimationTriangle = DecimationTriangle;
  28894. var DecimationVertex = (function () {
  28895. function DecimationVertex(position, id) {
  28896. this.position = position;
  28897. this.id = id;
  28898. this.isBorder = true;
  28899. this.q = new QuadraticMatrix();
  28900. this.triangleCount = 0;
  28901. this.triangleStart = 0;
  28902. this.originalOffsets = [];
  28903. }
  28904. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28905. this.position.copyFrom(newPosition);
  28906. };
  28907. return DecimationVertex;
  28908. })();
  28909. BABYLON.DecimationVertex = DecimationVertex;
  28910. var QuadraticMatrix = (function () {
  28911. function QuadraticMatrix(data) {
  28912. this.data = new Array(10);
  28913. for (var i = 0; i < 10; ++i) {
  28914. if (data && data[i]) {
  28915. this.data[i] = data[i];
  28916. }
  28917. else {
  28918. this.data[i] = 0;
  28919. }
  28920. }
  28921. }
  28922. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28923. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28924. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28925. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28926. return det;
  28927. };
  28928. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28929. for (var i = 0; i < 10; ++i) {
  28930. this.data[i] += matrix.data[i];
  28931. }
  28932. };
  28933. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28934. for (var i = 0; i < 10; ++i) {
  28935. this.data[i] += data[i];
  28936. }
  28937. };
  28938. QuadraticMatrix.prototype.add = function (matrix) {
  28939. var m = new QuadraticMatrix();
  28940. for (var i = 0; i < 10; ++i) {
  28941. m.data[i] = this.data[i] + matrix.data[i];
  28942. }
  28943. return m;
  28944. };
  28945. QuadraticMatrix.FromData = function (a, b, c, d) {
  28946. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28947. };
  28948. //returning an array to avoid garbage collection
  28949. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28950. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28951. };
  28952. return QuadraticMatrix;
  28953. })();
  28954. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28955. var Reference = (function () {
  28956. function Reference(vertexId, triangleId) {
  28957. this.vertexId = vertexId;
  28958. this.triangleId = triangleId;
  28959. }
  28960. return Reference;
  28961. })();
  28962. BABYLON.Reference = Reference;
  28963. /**
  28964. * An implementation of the Quadratic Error simplification algorithm.
  28965. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28966. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28967. * @author RaananW
  28968. */
  28969. var QuadraticErrorSimplification = (function () {
  28970. function QuadraticErrorSimplification(_mesh) {
  28971. this._mesh = _mesh;
  28972. this.initialized = false;
  28973. this.syncIterations = 5000;
  28974. this.aggressiveness = 7;
  28975. this.decimationIterations = 100;
  28976. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28977. }
  28978. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28979. var _this = this;
  28980. this.initDecimatedMesh();
  28981. //iterating through the submeshes array, one after the other.
  28982. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28983. _this.initWithMesh(loop.index, function () {
  28984. _this.runDecimation(settings, loop.index, function () {
  28985. loop.executeNext();
  28986. });
  28987. }, settings.optimizeMesh);
  28988. }, function () {
  28989. setTimeout(function () {
  28990. successCallback(_this._reconstructedMesh);
  28991. }, 0);
  28992. });
  28993. };
  28994. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28995. var _this = this;
  28996. var gCount = 0;
  28997. triangle.vertices.forEach(function (vertex) {
  28998. var count = 0;
  28999. var vPos = vertex.position;
  29000. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29001. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29002. ++count;
  29003. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29004. ++count;
  29005. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29006. ++count;
  29007. if (count > 1) {
  29008. ++gCount;
  29009. }
  29010. ;
  29011. });
  29012. if (gCount > 1) {
  29013. console.log(triangle, gCount);
  29014. }
  29015. return gCount > 1;
  29016. };
  29017. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29018. var _this = this;
  29019. var targetCount = ~~(this.triangles.length * settings.quality);
  29020. var deletedTriangles = 0;
  29021. var triangleCount = this.triangles.length;
  29022. var iterationFunction = function (iteration, callback) {
  29023. setTimeout(function () {
  29024. if (iteration % 5 === 0) {
  29025. _this.updateMesh(iteration === 0);
  29026. }
  29027. for (var i = 0; i < _this.triangles.length; ++i) {
  29028. _this.triangles[i].isDirty = false;
  29029. }
  29030. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29031. var trianglesIterator = function (i) {
  29032. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29033. var t = _this.triangles[tIdx];
  29034. if (!t)
  29035. return;
  29036. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29037. return;
  29038. }
  29039. for (var j = 0; j < 3; ++j) {
  29040. if (t.error[j] < threshold) {
  29041. var deleted0 = [];
  29042. var deleted1 = [];
  29043. var v0 = t.vertices[j];
  29044. var v1 = t.vertices[(j + 1) % 3];
  29045. if (v0.isBorder !== v1.isBorder)
  29046. continue;
  29047. var p = BABYLON.Vector3.Zero();
  29048. var n = BABYLON.Vector3.Zero();
  29049. var uv = BABYLON.Vector2.Zero();
  29050. var color = new BABYLON.Color4(0, 0, 0, 1);
  29051. _this.calculateError(v0, v1, p, n, uv, color);
  29052. var delTr = [];
  29053. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29054. continue;
  29055. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29056. continue;
  29057. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29058. continue;
  29059. var uniqueArray = [];
  29060. delTr.forEach(function (deletedT) {
  29061. if (uniqueArray.indexOf(deletedT) === -1) {
  29062. deletedT.deletePending = true;
  29063. uniqueArray.push(deletedT);
  29064. }
  29065. });
  29066. if (uniqueArray.length % 2 !== 0) {
  29067. continue;
  29068. }
  29069. v0.q = v1.q.add(v0.q);
  29070. v0.updatePosition(p);
  29071. var tStart = _this.references.length;
  29072. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29073. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29074. var tCount = _this.references.length - tStart;
  29075. if (tCount <= v0.triangleCount) {
  29076. if (tCount) {
  29077. for (var c = 0; c < tCount; c++) {
  29078. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29079. }
  29080. }
  29081. }
  29082. else {
  29083. v0.triangleStart = tStart;
  29084. }
  29085. v0.triangleCount = tCount;
  29086. break;
  29087. }
  29088. }
  29089. };
  29090. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29091. }, 0);
  29092. };
  29093. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29094. if (triangleCount - deletedTriangles <= targetCount)
  29095. loop.breakLoop();
  29096. else {
  29097. iterationFunction(loop.index, function () {
  29098. loop.executeNext();
  29099. });
  29100. }
  29101. }, function () {
  29102. setTimeout(function () {
  29103. //reconstruct this part of the mesh
  29104. _this.reconstructMesh(submeshIndex);
  29105. successCallback();
  29106. }, 0);
  29107. });
  29108. };
  29109. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29110. var _this = this;
  29111. this.vertices = [];
  29112. this.triangles = [];
  29113. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29114. var indices = this._mesh.getIndices();
  29115. var submesh = this._mesh.subMeshes[submeshIndex];
  29116. var findInVertices = function (positionToSearch) {
  29117. if (optimizeMesh) {
  29118. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29119. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29120. return _this.vertices[ii];
  29121. }
  29122. }
  29123. }
  29124. return null;
  29125. };
  29126. var vertexReferences = [];
  29127. var vertexInit = function (i) {
  29128. var offset = i + submesh.verticesStart;
  29129. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29130. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29131. vertex.originalOffsets.push(offset);
  29132. if (vertex.id === _this.vertices.length) {
  29133. _this.vertices.push(vertex);
  29134. }
  29135. vertexReferences.push(vertex.id);
  29136. };
  29137. //var totalVertices = mesh.getTotalVertices();
  29138. var totalVertices = submesh.verticesCount;
  29139. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29140. var indicesInit = function (i) {
  29141. var offset = (submesh.indexStart / 3) + i;
  29142. var pos = (offset * 3);
  29143. var i0 = indices[pos + 0];
  29144. var i1 = indices[pos + 1];
  29145. var i2 = indices[pos + 2];
  29146. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29147. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29148. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29149. var triangle = new DecimationTriangle([v0, v1, v2]);
  29150. triangle.originalOffset = pos;
  29151. _this.triangles.push(triangle);
  29152. };
  29153. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29154. _this.init(callback);
  29155. });
  29156. });
  29157. };
  29158. QuadraticErrorSimplification.prototype.init = function (callback) {
  29159. var _this = this;
  29160. var triangleInit1 = function (i) {
  29161. var t = _this.triangles[i];
  29162. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29163. for (var j = 0; j < 3; j++) {
  29164. 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))));
  29165. }
  29166. };
  29167. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29168. var triangleInit2 = function (i) {
  29169. var t = _this.triangles[i];
  29170. for (var j = 0; j < 3; ++j) {
  29171. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29172. }
  29173. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29174. };
  29175. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29176. _this.initialized = true;
  29177. callback();
  29178. });
  29179. });
  29180. };
  29181. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29182. var newTriangles = [];
  29183. var i;
  29184. for (i = 0; i < this.vertices.length; ++i) {
  29185. this.vertices[i].triangleCount = 0;
  29186. }
  29187. var t;
  29188. var j;
  29189. for (i = 0; i < this.triangles.length; ++i) {
  29190. if (!this.triangles[i].deleted) {
  29191. t = this.triangles[i];
  29192. for (j = 0; j < 3; ++j) {
  29193. t.vertices[j].triangleCount = 1;
  29194. }
  29195. newTriangles.push(t);
  29196. }
  29197. }
  29198. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29199. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29200. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29201. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29202. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29203. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29204. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29205. var vertexCount = 0;
  29206. for (i = 0; i < this.vertices.length; ++i) {
  29207. var vertex = this.vertices[i];
  29208. vertex.id = vertexCount;
  29209. if (vertex.triangleCount) {
  29210. vertex.originalOffsets.forEach(function (originalOffset) {
  29211. newPositionData.push(vertex.position.x);
  29212. newPositionData.push(vertex.position.y);
  29213. newPositionData.push(vertex.position.z);
  29214. newNormalData.push(normalData[originalOffset * 3]);
  29215. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29216. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29217. if (uvs && uvs.length) {
  29218. newUVsData.push(uvs[(originalOffset * 2)]);
  29219. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29220. }
  29221. else if (colorsData && colorsData.length) {
  29222. newColorsData.push(colorsData[(originalOffset * 4)]);
  29223. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29224. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29225. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29226. }
  29227. ++vertexCount;
  29228. });
  29229. }
  29230. }
  29231. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29232. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29233. var submeshesArray = this._reconstructedMesh.subMeshes;
  29234. this._reconstructedMesh.subMeshes = [];
  29235. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29236. var originalIndices = this._mesh.getIndices();
  29237. for (i = 0; i < newTriangles.length; ++i) {
  29238. t = newTriangles[i]; //now get the new referencing point for each vertex
  29239. [0, 1, 2].forEach(function (idx) {
  29240. var id = originalIndices[t.originalOffset + idx];
  29241. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29242. if (offset < 0)
  29243. offset = 0;
  29244. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29245. });
  29246. }
  29247. //overwriting the old vertex buffers and indices.
  29248. this._reconstructedMesh.setIndices(newIndicesArray);
  29249. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29250. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29251. if (newUVsData.length > 0)
  29252. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29253. if (newColorsData.length > 0)
  29254. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29255. //create submesh
  29256. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29257. if (submeshIndex > 0) {
  29258. this._reconstructedMesh.subMeshes = [];
  29259. submeshesArray.forEach(function (submesh) {
  29260. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29261. });
  29262. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29263. }
  29264. };
  29265. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29266. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29267. this._reconstructedMesh.material = this._mesh.material;
  29268. this._reconstructedMesh.parent = this._mesh.parent;
  29269. this._reconstructedMesh.isVisible = false;
  29270. };
  29271. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29272. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29273. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29274. if (t.deleted)
  29275. continue;
  29276. var s = this.references[vertex1.triangleStart + i].vertexId;
  29277. var v1 = t.vertices[(s + 1) % 3];
  29278. var v2 = t.vertices[(s + 2) % 3];
  29279. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29280. deletedArray[i] = true;
  29281. delTr.push(t);
  29282. continue;
  29283. }
  29284. var d1 = v1.position.subtract(point);
  29285. d1 = d1.normalize();
  29286. var d2 = v2.position.subtract(point);
  29287. d2 = d2.normalize();
  29288. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29289. return true;
  29290. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29291. deletedArray[i] = false;
  29292. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29293. return true;
  29294. }
  29295. return false;
  29296. };
  29297. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29298. var newDeleted = deletedTriangles;
  29299. for (var i = 0; i < vertex.triangleCount; ++i) {
  29300. var ref = this.references[vertex.triangleStart + i];
  29301. var t = this.triangles[ref.triangleId];
  29302. if (t.deleted)
  29303. continue;
  29304. if (deletedArray[i] && t.deletePending) {
  29305. t.deleted = true;
  29306. newDeleted++;
  29307. continue;
  29308. }
  29309. t.vertices[ref.vertexId] = origVertex;
  29310. t.isDirty = true;
  29311. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29312. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29313. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29314. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29315. this.references.push(ref);
  29316. }
  29317. return newDeleted;
  29318. };
  29319. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29320. for (var i = 0; i < this.vertices.length; ++i) {
  29321. var vCount = [];
  29322. var vId = [];
  29323. var v = this.vertices[i];
  29324. var j;
  29325. for (j = 0; j < v.triangleCount; ++j) {
  29326. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29327. for (var ii = 0; ii < 3; ii++) {
  29328. var ofs = 0;
  29329. var vv = triangle.vertices[ii];
  29330. while (ofs < vCount.length) {
  29331. if (vId[ofs] === vv.id)
  29332. break;
  29333. ++ofs;
  29334. }
  29335. if (ofs === vCount.length) {
  29336. vCount.push(1);
  29337. vId.push(vv.id);
  29338. }
  29339. else {
  29340. vCount[ofs]++;
  29341. }
  29342. }
  29343. }
  29344. for (j = 0; j < vCount.length; ++j) {
  29345. if (vCount[j] === 1) {
  29346. this.vertices[vId[j]].isBorder = true;
  29347. }
  29348. else {
  29349. this.vertices[vId[j]].isBorder = false;
  29350. }
  29351. }
  29352. }
  29353. };
  29354. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29355. if (identifyBorders === void 0) { identifyBorders = false; }
  29356. var i;
  29357. if (!identifyBorders) {
  29358. var newTrianglesVector = [];
  29359. for (i = 0; i < this.triangles.length; ++i) {
  29360. if (!this.triangles[i].deleted) {
  29361. newTrianglesVector.push(this.triangles[i]);
  29362. }
  29363. }
  29364. this.triangles = newTrianglesVector;
  29365. }
  29366. for (i = 0; i < this.vertices.length; ++i) {
  29367. this.vertices[i].triangleCount = 0;
  29368. this.vertices[i].triangleStart = 0;
  29369. }
  29370. var t;
  29371. var j;
  29372. var v;
  29373. for (i = 0; i < this.triangles.length; ++i) {
  29374. t = this.triangles[i];
  29375. for (j = 0; j < 3; ++j) {
  29376. v = t.vertices[j];
  29377. v.triangleCount++;
  29378. }
  29379. }
  29380. var tStart = 0;
  29381. for (i = 0; i < this.vertices.length; ++i) {
  29382. this.vertices[i].triangleStart = tStart;
  29383. tStart += this.vertices[i].triangleCount;
  29384. this.vertices[i].triangleCount = 0;
  29385. }
  29386. var newReferences = new Array(this.triangles.length * 3);
  29387. for (i = 0; i < this.triangles.length; ++i) {
  29388. t = this.triangles[i];
  29389. for (j = 0; j < 3; ++j) {
  29390. v = t.vertices[j];
  29391. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29392. v.triangleCount++;
  29393. }
  29394. }
  29395. this.references = newReferences;
  29396. if (identifyBorders) {
  29397. this.identifyBorder();
  29398. }
  29399. };
  29400. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29401. var x = point.x;
  29402. var y = point.y;
  29403. var z = point.z;
  29404. 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
  29405. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29406. };
  29407. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29408. var q = vertex1.q.add(vertex2.q);
  29409. var border = vertex1.isBorder && vertex2.isBorder;
  29410. var error = 0;
  29411. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29412. if (qDet !== 0 && !border) {
  29413. if (!pointResult) {
  29414. pointResult = BABYLON.Vector3.Zero();
  29415. }
  29416. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29417. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29418. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29419. error = this.vertexError(q, pointResult);
  29420. }
  29421. else {
  29422. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29423. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29424. var error1 = this.vertexError(q, vertex1.position);
  29425. var error2 = this.vertexError(q, vertex2.position);
  29426. var error3 = this.vertexError(q, p3);
  29427. error = Math.min(error1, error2, error3);
  29428. if (error === error1) {
  29429. if (pointResult) {
  29430. pointResult.copyFrom(vertex1.position);
  29431. }
  29432. }
  29433. else if (error === error2) {
  29434. if (pointResult) {
  29435. pointResult.copyFrom(vertex2.position);
  29436. }
  29437. }
  29438. else {
  29439. if (pointResult) {
  29440. pointResult.copyFrom(p3);
  29441. }
  29442. }
  29443. }
  29444. return error;
  29445. };
  29446. return QuadraticErrorSimplification;
  29447. })();
  29448. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29449. })(BABYLON || (BABYLON = {}));
  29450. var BABYLON;
  29451. (function (BABYLON) {
  29452. var serializeLight = function (light) {
  29453. var serializationObject = {};
  29454. serializationObject.name = light.name;
  29455. serializationObject.id = light.id;
  29456. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29457. if (light instanceof BABYLON.PointLight) {
  29458. serializationObject.type = 0;
  29459. serializationObject.position = (light).position.asArray();
  29460. }
  29461. else if (light instanceof BABYLON.DirectionalLight) {
  29462. serializationObject.type = 1;
  29463. var directionalLight = light;
  29464. serializationObject.position = directionalLight.position.asArray();
  29465. serializationObject.direction = directionalLight.direction.asArray();
  29466. }
  29467. else if (light instanceof BABYLON.SpotLight) {
  29468. serializationObject.type = 2;
  29469. var spotLight = light;
  29470. serializationObject.position = spotLight.position.asArray();
  29471. serializationObject.direction = spotLight.position.asArray();
  29472. serializationObject.angle = spotLight.angle;
  29473. serializationObject.exponent = spotLight.exponent;
  29474. }
  29475. else if (light instanceof BABYLON.HemisphericLight) {
  29476. serializationObject.type = 3;
  29477. var hemisphericLight = light;
  29478. serializationObject.direction = hemisphericLight.direction.asArray();
  29479. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29480. }
  29481. if (light.intensity) {
  29482. serializationObject.intensity = light.intensity;
  29483. }
  29484. serializationObject.range = light.range;
  29485. serializationObject.diffuse = light.diffuse.asArray();
  29486. serializationObject.specular = light.specular.asArray();
  29487. return serializationObject;
  29488. };
  29489. var serializeFresnelParameter = function (fresnelParameter) {
  29490. var serializationObject = {};
  29491. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29492. serializationObject.leftColor = fresnelParameter.leftColor;
  29493. serializationObject.rightColor = fresnelParameter.rightColor;
  29494. serializationObject.bias = fresnelParameter.bias;
  29495. serializationObject.power = fresnelParameter.power;
  29496. return serializationObject;
  29497. };
  29498. var serializeAnimation;
  29499. var appendAnimations = function (source, destination) {
  29500. if (source.animations) {
  29501. destination.animations = [];
  29502. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29503. var animation = source.animations[animationIndex];
  29504. destination.animations.push(serializeAnimation(animation));
  29505. }
  29506. }
  29507. };
  29508. var serializeCamera = function (camera) {
  29509. var serializationObject = {};
  29510. serializationObject.name = camera.name;
  29511. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29512. serializationObject.id = camera.id;
  29513. serializationObject.position = camera.position.asArray();
  29514. // Parent
  29515. if (camera.parent) {
  29516. serializationObject.parentId = camera.parent.id;
  29517. }
  29518. serializationObject.fov = camera.fov;
  29519. serializationObject.minZ = camera.minZ;
  29520. serializationObject.maxZ = camera.maxZ;
  29521. serializationObject.inertia = camera.inertia;
  29522. //setting the type
  29523. if (camera instanceof BABYLON.FreeCamera) {
  29524. serializationObject.type = "FreeCamera";
  29525. }
  29526. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29527. serializationObject.type = "ArcRotateCamera";
  29528. }
  29529. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29530. serializationObject.type = "AnaglyphArcRotateCamera";
  29531. }
  29532. else if (camera instanceof BABYLON.GamepadCamera) {
  29533. serializationObject.type = "GamepadCamera";
  29534. }
  29535. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29536. serializationObject.type = "AnaglyphFreeCamera";
  29537. }
  29538. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29539. serializationObject.type = "DeviceOrientationCamera";
  29540. }
  29541. else if (camera instanceof BABYLON.FollowCamera) {
  29542. serializationObject.type = "FollowCamera";
  29543. }
  29544. else if (camera instanceof BABYLON.TouchCamera) {
  29545. serializationObject.type = "TouchCamera";
  29546. }
  29547. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29548. serializationObject.type = "VirtualJoysticksCamera";
  29549. }
  29550. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29551. serializationObject.type = "WebVRFreeCamera";
  29552. }
  29553. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29554. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29555. }
  29556. //special properties of specific cameras
  29557. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29558. var arcCamera = camera;
  29559. serializationObject.alpha = arcCamera.alpha;
  29560. serializationObject.beta = arcCamera.beta;
  29561. serializationObject.radius = arcCamera.radius;
  29562. if (arcCamera.target && arcCamera.target.id) {
  29563. serializationObject.lockedTargetId = arcCamera.target.id;
  29564. }
  29565. }
  29566. else if (camera instanceof BABYLON.FollowCamera) {
  29567. var followCam = camera;
  29568. serializationObject.radius = followCam.radius;
  29569. serializationObject.heightOffset = followCam.heightOffset;
  29570. serializationObject.rotationOffset = followCam.rotationOffset;
  29571. }
  29572. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29573. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  29574. if (camera['_interaxialDistance'] !== undefined) {
  29575. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29576. }
  29577. }
  29578. //general properties that not all cameras have. The [] is due to typescript's type safety
  29579. if (camera['speed'] !== undefined) {
  29580. serializationObject.speed = camera['speed'];
  29581. }
  29582. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29583. serializationObject.target = camera['target'].asArray();
  29584. }
  29585. // Target
  29586. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29587. serializationObject.rotation = camera['rotation'].asArray();
  29588. }
  29589. // Locked target
  29590. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29591. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29592. }
  29593. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29594. serializationObject.applyGravity = camera['applyGravity'] || false;
  29595. if (camera['ellipsoid']) {
  29596. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29597. }
  29598. // Animations
  29599. appendAnimations(camera, serializationObject);
  29600. // Layer mask
  29601. serializationObject.layerMask = camera.layerMask;
  29602. return serializationObject;
  29603. };
  29604. serializeAnimation = function (animation) {
  29605. var serializationObject = {};
  29606. serializationObject.name = animation.name;
  29607. serializationObject.property = animation.targetProperty;
  29608. serializationObject.framePerSecond = animation.framePerSecond;
  29609. serializationObject.dataType = animation.dataType;
  29610. serializationObject.loopBehavior = animation.loopMode;
  29611. var dataType = animation.dataType;
  29612. serializationObject.keys = [];
  29613. var keys = animation.getKeys();
  29614. for (var index = 0; index < keys.length; index++) {
  29615. var animationKey = keys[index];
  29616. var key = {};
  29617. key.frame = animationKey.frame;
  29618. switch (dataType) {
  29619. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29620. key.values = [animationKey.value];
  29621. break;
  29622. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29623. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29624. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29625. key.values = animationKey.value.asArray();
  29626. break;
  29627. }
  29628. serializationObject.keys.push(key);
  29629. }
  29630. return serializationObject;
  29631. };
  29632. var serializeMultiMaterial = function (material) {
  29633. var serializationObject = {};
  29634. serializationObject.name = material.name;
  29635. serializationObject.id = material.id;
  29636. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29637. serializationObject.materials = [];
  29638. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29639. var subMat = material.subMaterials[matIndex];
  29640. if (subMat) {
  29641. serializationObject.materials.push(subMat.id);
  29642. }
  29643. else {
  29644. serializationObject.materials.push(null);
  29645. }
  29646. }
  29647. return serializationObject;
  29648. };
  29649. var serializeTexture;
  29650. var serializeMaterial = function (material) {
  29651. var serializationObject = {};
  29652. serializationObject.name = material.name;
  29653. serializationObject.ambient = material.ambientColor.asArray();
  29654. serializationObject.diffuse = material.diffuseColor.asArray();
  29655. serializationObject.specular = material.specularColor.asArray();
  29656. serializationObject.specularPower = material.specularPower;
  29657. serializationObject.emissive = material.emissiveColor.asArray();
  29658. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29659. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29660. serializationObject.alpha = material.alpha;
  29661. serializationObject.id = material.id;
  29662. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29663. serializationObject.backFaceCulling = material.backFaceCulling;
  29664. if (material.diffuseTexture) {
  29665. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29666. }
  29667. if (material.diffuseFresnelParameters) {
  29668. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29669. }
  29670. if (material.ambientTexture) {
  29671. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29672. }
  29673. if (material.opacityTexture) {
  29674. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29675. }
  29676. if (material.opacityFresnelParameters) {
  29677. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29678. }
  29679. if (material.reflectionTexture) {
  29680. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29681. }
  29682. if (material.reflectionFresnelParameters) {
  29683. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29684. }
  29685. if (material.emissiveTexture) {
  29686. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29687. }
  29688. if (material.lightmapTexture) {
  29689. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29690. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29691. }
  29692. if (material.emissiveFresnelParameters) {
  29693. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29694. }
  29695. if (material.specularTexture) {
  29696. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29697. }
  29698. if (material.bumpTexture) {
  29699. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29700. }
  29701. return serializationObject;
  29702. };
  29703. serializeTexture = function (texture) {
  29704. var serializationObject = {};
  29705. if (!texture.name) {
  29706. return null;
  29707. }
  29708. if (texture instanceof BABYLON.CubeTexture) {
  29709. serializationObject.name = texture.name;
  29710. serializationObject.hasAlpha = texture.hasAlpha;
  29711. serializationObject.isCube = true;
  29712. serializationObject.level = texture.level;
  29713. serializationObject.coordinatesMode = texture.coordinatesMode;
  29714. return serializationObject;
  29715. }
  29716. var index;
  29717. if (texture instanceof BABYLON.MirrorTexture) {
  29718. var mirrorTexture = texture;
  29719. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29720. serializationObject.renderList = [];
  29721. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29722. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29723. }
  29724. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29725. }
  29726. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29727. var renderTargetTexture = texture;
  29728. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29729. serializationObject.renderList = [];
  29730. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29731. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29732. }
  29733. }
  29734. var regularTexture = texture;
  29735. serializationObject.name = texture.name;
  29736. serializationObject.hasAlpha = texture.hasAlpha;
  29737. serializationObject.level = texture.level;
  29738. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29739. serializationObject.coordinatesMode = texture.coordinatesMode;
  29740. serializationObject.uOffset = regularTexture.uOffset;
  29741. serializationObject.vOffset = regularTexture.vOffset;
  29742. serializationObject.uScale = regularTexture.uScale;
  29743. serializationObject.vScale = regularTexture.vScale;
  29744. serializationObject.uAng = regularTexture.uAng;
  29745. serializationObject.vAng = regularTexture.vAng;
  29746. serializationObject.wAng = regularTexture.wAng;
  29747. serializationObject.wrapU = texture.wrapU;
  29748. serializationObject.wrapV = texture.wrapV;
  29749. // Animations
  29750. appendAnimations(texture, serializationObject);
  29751. return serializationObject;
  29752. };
  29753. var serializeSkeleton = function (skeleton) {
  29754. var serializationObject = {};
  29755. serializationObject.name = skeleton.name;
  29756. serializationObject.id = skeleton.id;
  29757. serializationObject.bones = [];
  29758. for (var index = 0; index < skeleton.bones.length; index++) {
  29759. var bone = skeleton.bones[index];
  29760. var serializedBone = {
  29761. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29762. name: bone.name,
  29763. matrix: bone.getLocalMatrix().toArray()
  29764. };
  29765. serializationObject.bones.push(serializedBone);
  29766. if (bone.animations && bone.animations.length > 0) {
  29767. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29768. }
  29769. }
  29770. return serializationObject;
  29771. };
  29772. var serializeParticleSystem = function (particleSystem) {
  29773. var serializationObject = {};
  29774. serializationObject.emitterId = particleSystem.emitter.id;
  29775. serializationObject.capacity = particleSystem.getCapacity();
  29776. if (particleSystem.particleTexture) {
  29777. serializationObject.textureName = particleSystem.particleTexture.name;
  29778. }
  29779. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29780. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29781. serializationObject.minSize = particleSystem.minSize;
  29782. serializationObject.maxSize = particleSystem.maxSize;
  29783. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29784. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29785. serializationObject.emitRate = particleSystem.emitRate;
  29786. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29787. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29788. serializationObject.gravity = particleSystem.gravity.asArray();
  29789. serializationObject.direction1 = particleSystem.direction1.asArray();
  29790. serializationObject.direction2 = particleSystem.direction2.asArray();
  29791. serializationObject.color1 = particleSystem.color1.asArray();
  29792. serializationObject.color2 = particleSystem.color2.asArray();
  29793. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29794. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29795. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29796. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29797. serializationObject.blendMode = particleSystem.blendMode;
  29798. return serializationObject;
  29799. };
  29800. var serializeLensFlareSystem = function (lensFlareSystem) {
  29801. var serializationObject = {};
  29802. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29803. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29804. serializationObject.flares = [];
  29805. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29806. var flare = lensFlareSystem.lensFlares[index];
  29807. serializationObject.flares.push({
  29808. size: flare.size,
  29809. position: flare.position,
  29810. color: flare.color.asArray(),
  29811. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29812. });
  29813. }
  29814. return serializationObject;
  29815. };
  29816. var serializeShadowGenerator = function (light) {
  29817. var serializationObject = {};
  29818. var shadowGenerator = light.getShadowGenerator();
  29819. serializationObject.lightId = light.id;
  29820. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29821. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29822. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29823. serializationObject.renderList = [];
  29824. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29825. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29826. serializationObject.renderList.push(mesh.id);
  29827. }
  29828. return serializationObject;
  29829. };
  29830. var serializedGeometries = [];
  29831. var serializeVertexData;
  29832. var serializeTorusKnot;
  29833. var serializePlane;
  29834. var serializeGround;
  29835. var serializeTorus;
  29836. var serializeCylinder;
  29837. var serializeSphere;
  29838. var serializeBox;
  29839. var serializeGeometry = function (geometry, serializationGeometries) {
  29840. if (serializedGeometries[geometry.id]) {
  29841. return;
  29842. }
  29843. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29844. serializationGeometries.boxes.push(serializeBox(geometry));
  29845. }
  29846. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29847. serializationGeometries.spheres.push(serializeSphere(geometry));
  29848. }
  29849. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29850. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29851. }
  29852. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29853. serializationGeometries.toruses.push(serializeTorus(geometry));
  29854. }
  29855. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29856. serializationGeometries.grounds.push(serializeGround(geometry));
  29857. }
  29858. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29859. serializationGeometries.planes.push(serializePlane(geometry));
  29860. }
  29861. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29862. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29863. }
  29864. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29865. throw new Error("Unknown primitive type");
  29866. }
  29867. else {
  29868. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29869. }
  29870. serializedGeometries[geometry.id] = true;
  29871. };
  29872. var serializeGeometryBase = function (geometry) {
  29873. var serializationObject = {};
  29874. serializationObject.id = geometry.id;
  29875. if (BABYLON.Tags.HasTags(geometry)) {
  29876. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29877. }
  29878. return serializationObject;
  29879. };
  29880. serializeVertexData = function (vertexData) {
  29881. var serializationObject = serializeGeometryBase(vertexData);
  29882. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29883. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29884. }
  29885. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29886. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29887. }
  29888. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29889. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29890. }
  29891. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29892. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29893. }
  29894. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29895. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29896. }
  29897. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29898. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29899. }
  29900. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29901. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29902. }
  29903. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29904. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29905. }
  29906. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29907. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29908. }
  29909. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29910. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29911. serializationObject.matricesIndices._isExpanded = true;
  29912. }
  29913. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29914. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29915. }
  29916. serializationObject.indices = vertexData.getIndices();
  29917. return serializationObject;
  29918. };
  29919. var serializePrimitive = function (primitive) {
  29920. var serializationObject = serializeGeometryBase(primitive);
  29921. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29922. return serializationObject;
  29923. };
  29924. serializeBox = function (box) {
  29925. var serializationObject = serializePrimitive(box);
  29926. serializationObject.size = box.size;
  29927. return serializationObject;
  29928. };
  29929. serializeSphere = function (sphere) {
  29930. var serializationObject = serializePrimitive(sphere);
  29931. serializationObject.segments = sphere.segments;
  29932. serializationObject.diameter = sphere.diameter;
  29933. return serializationObject;
  29934. };
  29935. serializeCylinder = function (cylinder) {
  29936. var serializationObject = serializePrimitive(cylinder);
  29937. serializationObject.height = cylinder.height;
  29938. serializationObject.diameterTop = cylinder.diameterTop;
  29939. serializationObject.diameterBottom = cylinder.diameterBottom;
  29940. serializationObject.tessellation = cylinder.tessellation;
  29941. return serializationObject;
  29942. };
  29943. serializeTorus = function (torus) {
  29944. var serializationObject = serializePrimitive(torus);
  29945. serializationObject.diameter = torus.diameter;
  29946. serializationObject.thickness = torus.thickness;
  29947. serializationObject.tessellation = torus.tessellation;
  29948. return serializationObject;
  29949. };
  29950. serializeGround = function (ground) {
  29951. var serializationObject = serializePrimitive(ground);
  29952. serializationObject.width = ground.width;
  29953. serializationObject.height = ground.height;
  29954. serializationObject.subdivisions = ground.subdivisions;
  29955. return serializationObject;
  29956. };
  29957. serializePlane = function (plane) {
  29958. var serializationObject = serializePrimitive(plane);
  29959. serializationObject.size = plane.size;
  29960. return serializationObject;
  29961. };
  29962. serializeTorusKnot = function (torusKnot) {
  29963. var serializationObject = serializePrimitive(torusKnot);
  29964. serializationObject.radius = torusKnot.radius;
  29965. serializationObject.tube = torusKnot.tube;
  29966. serializationObject.radialSegments = torusKnot.radialSegments;
  29967. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29968. serializationObject.p = torusKnot.p;
  29969. serializationObject.q = torusKnot.q;
  29970. return serializationObject;
  29971. };
  29972. var serializeMesh = function (mesh, serializationScene) {
  29973. var serializationObject = {};
  29974. serializationObject.name = mesh.name;
  29975. serializationObject.id = mesh.id;
  29976. if (BABYLON.Tags.HasTags(mesh)) {
  29977. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29978. }
  29979. serializationObject.position = mesh.position.asArray();
  29980. if (mesh.rotationQuaternion) {
  29981. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29982. }
  29983. else if (mesh.rotation) {
  29984. serializationObject.rotation = mesh.rotation.asArray();
  29985. }
  29986. serializationObject.scaling = mesh.scaling.asArray();
  29987. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29988. serializationObject.isEnabled = mesh.isEnabled();
  29989. serializationObject.isVisible = mesh.isVisible;
  29990. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29991. serializationObject.pickable = mesh.isPickable;
  29992. serializationObject.receiveShadows = mesh.receiveShadows;
  29993. serializationObject.billboardMode = mesh.billboardMode;
  29994. serializationObject.visibility = mesh.visibility;
  29995. serializationObject.checkCollisions = mesh.checkCollisions;
  29996. // Parent
  29997. if (mesh.parent) {
  29998. serializationObject.parentId = mesh.parent.id;
  29999. }
  30000. // Geometry
  30001. var geometry = mesh._geometry;
  30002. if (geometry) {
  30003. var geometryId = geometry.id;
  30004. serializationObject.geometryId = geometryId;
  30005. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30006. // 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
  30007. serializeGeometry(geometry, serializationScene.geometries);
  30008. }
  30009. // SubMeshes
  30010. serializationObject.subMeshes = [];
  30011. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30012. var subMesh = mesh.subMeshes[subIndex];
  30013. serializationObject.subMeshes.push({
  30014. materialIndex: subMesh.materialIndex,
  30015. verticesStart: subMesh.verticesStart,
  30016. verticesCount: subMesh.verticesCount,
  30017. indexStart: subMesh.indexStart,
  30018. indexCount: subMesh.indexCount
  30019. });
  30020. }
  30021. }
  30022. // Material
  30023. if (mesh.material) {
  30024. serializationObject.materialId = mesh.material.id;
  30025. }
  30026. else {
  30027. mesh.material = null;
  30028. }
  30029. // Skeleton
  30030. if (mesh.skeleton) {
  30031. serializationObject.skeletonId = mesh.skeleton.id;
  30032. }
  30033. // Physics
  30034. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30035. serializationObject.physicsMass = mesh.getPhysicsMass();
  30036. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30037. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30038. switch (mesh.getPhysicsImpostor()) {
  30039. case BABYLON.PhysicsEngine.BoxImpostor:
  30040. serializationObject.physicsImpostor = 1;
  30041. break;
  30042. case BABYLON.PhysicsEngine.SphereImpostor:
  30043. serializationObject.physicsImpostor = 2;
  30044. break;
  30045. }
  30046. }
  30047. // Instances
  30048. serializationObject.instances = [];
  30049. for (var index = 0; index < mesh.instances.length; index++) {
  30050. var instance = mesh.instances[index];
  30051. var serializationInstance = {
  30052. name: instance.name,
  30053. position: instance.position.asArray(),
  30054. rotation: instance.rotation.asArray(),
  30055. rotationQuaternion: instance.rotationQuaternion.asArray(),
  30056. scaling: instance.scaling.asArray()
  30057. };
  30058. serializationObject.instances.push(serializationInstance);
  30059. // Animations
  30060. appendAnimations(instance, serializationInstance);
  30061. }
  30062. // Animations
  30063. appendAnimations(mesh, serializationObject);
  30064. // Layer mask
  30065. serializationObject.layerMask = mesh.layerMask;
  30066. return serializationObject;
  30067. };
  30068. var finalizeSingleMesh = function (mesh, serializationObject) {
  30069. //only works if the mesh is already loaded
  30070. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30071. //serialize material
  30072. if (mesh.material) {
  30073. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30074. serializationObject.materials = serializationObject.materials || [];
  30075. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30076. serializationObject.materials.push(serializeMaterial(mesh.material));
  30077. }
  30078. }
  30079. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30080. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30081. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30082. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  30083. }
  30084. }
  30085. }
  30086. //serialize geometry
  30087. var geometry = mesh._geometry;
  30088. if (geometry) {
  30089. if (!serializationObject.geometries) {
  30090. serializationObject.geometries = {};
  30091. serializationObject.geometries.boxes = [];
  30092. serializationObject.geometries.spheres = [];
  30093. serializationObject.geometries.cylinders = [];
  30094. serializationObject.geometries.toruses = [];
  30095. serializationObject.geometries.grounds = [];
  30096. serializationObject.geometries.planes = [];
  30097. serializationObject.geometries.torusKnots = [];
  30098. serializationObject.geometries.vertexData = [];
  30099. }
  30100. serializeGeometry(geometry, serializationObject.geometries);
  30101. }
  30102. // Skeletons
  30103. if (mesh.skeleton) {
  30104. serializationObject.skeletons = serializationObject.skeletons || [];
  30105. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  30106. }
  30107. //serialize the actual mesh
  30108. serializationObject.meshes = serializationObject.meshes || [];
  30109. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30110. }
  30111. };
  30112. var SceneSerializer = (function () {
  30113. function SceneSerializer() {
  30114. }
  30115. SceneSerializer.Serialize = function (scene) {
  30116. var serializationObject = {};
  30117. // Scene
  30118. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30119. serializationObject.autoClear = scene.autoClear;
  30120. serializationObject.clearColor = scene.clearColor.asArray();
  30121. serializationObject.ambientColor = scene.ambientColor.asArray();
  30122. serializationObject.gravity = scene.gravity.asArray();
  30123. // Fog
  30124. if (scene.fogMode && scene.fogMode !== 0) {
  30125. serializationObject.fogMode = scene.fogMode;
  30126. serializationObject.fogColor = scene.fogColor.asArray();
  30127. serializationObject.fogStart = scene.fogStart;
  30128. serializationObject.fogEnd = scene.fogEnd;
  30129. serializationObject.fogDensity = scene.fogDensity;
  30130. }
  30131. // Lights
  30132. serializationObject.lights = [];
  30133. var index;
  30134. var light;
  30135. for (index = 0; index < scene.lights.length; index++) {
  30136. light = scene.lights[index];
  30137. serializationObject.lights.push(serializeLight(light));
  30138. }
  30139. // Cameras
  30140. serializationObject.cameras = [];
  30141. for (index = 0; index < scene.cameras.length; index++) {
  30142. var camera = scene.cameras[index];
  30143. serializationObject.cameras.push(serializeCamera(camera));
  30144. }
  30145. if (scene.activeCamera) {
  30146. serializationObject.activeCameraID = scene.activeCamera.id;
  30147. }
  30148. // Materials
  30149. serializationObject.materials = [];
  30150. serializationObject.multiMaterials = [];
  30151. var material;
  30152. for (index = 0; index < scene.materials.length; index++) {
  30153. material = scene.materials[index];
  30154. serializationObject.materials.push(serializeMaterial(material));
  30155. }
  30156. // MultiMaterials
  30157. serializationObject.multiMaterials = [];
  30158. for (index = 0; index < scene.multiMaterials.length; index++) {
  30159. var multiMaterial = scene.multiMaterials[index];
  30160. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  30161. }
  30162. for (index = 0; index < scene.materials.length; index++) {
  30163. material = scene.materials[index];
  30164. if (material instanceof BABYLON.StandardMaterial) {
  30165. serializationObject.materials.push(serializeMaterial(material));
  30166. }
  30167. else if (material instanceof BABYLON.MultiMaterial) {
  30168. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  30169. }
  30170. }
  30171. // Skeletons
  30172. serializationObject.skeletons = [];
  30173. for (index = 0; index < scene.skeletons.length; index++) {
  30174. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  30175. }
  30176. // Geometries
  30177. serializationObject.geometries = {};
  30178. serializationObject.geometries.boxes = [];
  30179. serializationObject.geometries.spheres = [];
  30180. serializationObject.geometries.cylinders = [];
  30181. serializationObject.geometries.toruses = [];
  30182. serializationObject.geometries.grounds = [];
  30183. serializationObject.geometries.planes = [];
  30184. serializationObject.geometries.torusKnots = [];
  30185. serializationObject.geometries.vertexData = [];
  30186. serializedGeometries = [];
  30187. var geometries = scene.getGeometries();
  30188. for (index = 0; index < geometries.length; index++) {
  30189. var geometry = geometries[index];
  30190. if (geometry.isReady()) {
  30191. serializeGeometry(geometry, serializationObject.geometries);
  30192. }
  30193. }
  30194. // Meshes
  30195. serializationObject.meshes = [];
  30196. for (index = 0; index < scene.meshes.length; index++) {
  30197. var abstractMesh = scene.meshes[index];
  30198. if (abstractMesh instanceof BABYLON.Mesh) {
  30199. var mesh = abstractMesh;
  30200. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30201. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30202. }
  30203. }
  30204. }
  30205. // Particles Systems
  30206. serializationObject.particleSystems = [];
  30207. for (index = 0; index < scene.particleSystems.length; index++) {
  30208. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  30209. }
  30210. // Lens flares
  30211. serializationObject.lensFlareSystems = [];
  30212. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30213. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30214. }
  30215. // Shadows
  30216. serializationObject.shadowGenerators = [];
  30217. for (index = 0; index < scene.lights.length; index++) {
  30218. light = scene.lights[index];
  30219. if (light.getShadowGenerator()) {
  30220. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30221. }
  30222. }
  30223. return serializationObject;
  30224. };
  30225. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30226. if (withParents === void 0) { withParents = false; }
  30227. if (withChildren === void 0) { withChildren = false; }
  30228. var serializationObject = {};
  30229. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30230. if (withParents || withChildren) {
  30231. //deliberate for loop! not for each, appended should be processed as well.
  30232. for (var i = 0; i < toSerialize.length; ++i) {
  30233. if (withChildren) {
  30234. toSerialize[i].getDescendants().forEach(function (node) {
  30235. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30236. toSerialize.push(node);
  30237. }
  30238. });
  30239. }
  30240. //make sure the array doesn't contain the object already
  30241. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30242. toSerialize.push(toSerialize[i].parent);
  30243. }
  30244. }
  30245. }
  30246. toSerialize.forEach(function (mesh) {
  30247. finalizeSingleMesh(mesh, serializationObject);
  30248. });
  30249. return serializationObject;
  30250. };
  30251. return SceneSerializer;
  30252. })();
  30253. BABYLON.SceneSerializer = SceneSerializer;
  30254. })(BABYLON || (BABYLON = {}));
  30255. var BABYLON;
  30256. (function (BABYLON) {
  30257. // Unique ID when we import meshes from Babylon to CSG
  30258. var currentCSGMeshId = 0;
  30259. // # class Vertex
  30260. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30261. // one to provide additional features like texture coordinates and vertex
  30262. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30263. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30264. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30265. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30266. // is not used anywhere else.
  30267. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30268. var Vertex = (function () {
  30269. function Vertex(pos, normal, uv) {
  30270. this.pos = pos;
  30271. this.normal = normal;
  30272. this.uv = uv;
  30273. }
  30274. Vertex.prototype.clone = function () {
  30275. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30276. };
  30277. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30278. // orientation of a polygon is flipped.
  30279. Vertex.prototype.flip = function () {
  30280. this.normal = this.normal.scale(-1);
  30281. };
  30282. // Create a new vertex between this vertex and `other` by linearly
  30283. // interpolating all properties using a parameter of `t`. Subclasses should
  30284. // override this to interpolate additional properties.
  30285. Vertex.prototype.interpolate = function (other, t) {
  30286. 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));
  30287. };
  30288. return Vertex;
  30289. })();
  30290. // # class Plane
  30291. // Represents a plane in 3D space.
  30292. var Plane = (function () {
  30293. function Plane(normal, w) {
  30294. this.normal = normal;
  30295. this.w = w;
  30296. }
  30297. Plane.FromPoints = function (a, b, c) {
  30298. var v0 = c.subtract(a);
  30299. var v1 = b.subtract(a);
  30300. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30301. return null;
  30302. }
  30303. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30304. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30305. };
  30306. Plane.prototype.clone = function () {
  30307. return new Plane(this.normal.clone(), this.w);
  30308. };
  30309. Plane.prototype.flip = function () {
  30310. this.normal.scaleInPlace(-1);
  30311. this.w = -this.w;
  30312. };
  30313. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30314. // fragments in the appropriate lists. Coplanar polygons go into either
  30315. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30316. // respect to this plane. Polygons in front or in back of this plane go into
  30317. // either `front` or `back`.
  30318. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30319. var COPLANAR = 0;
  30320. var FRONT = 1;
  30321. var BACK = 2;
  30322. var SPANNING = 3;
  30323. // Classify each point as well as the entire polygon into one of the above
  30324. // four classes.
  30325. var polygonType = 0;
  30326. var types = [];
  30327. var i;
  30328. var t;
  30329. for (i = 0; i < polygon.vertices.length; i++) {
  30330. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30331. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30332. polygonType |= type;
  30333. types.push(type);
  30334. }
  30335. // Put the polygon in the correct list, splitting it when necessary.
  30336. switch (polygonType) {
  30337. case COPLANAR:
  30338. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30339. break;
  30340. case FRONT:
  30341. front.push(polygon);
  30342. break;
  30343. case BACK:
  30344. back.push(polygon);
  30345. break;
  30346. case SPANNING:
  30347. var f = [], b = [];
  30348. for (i = 0; i < polygon.vertices.length; i++) {
  30349. var j = (i + 1) % polygon.vertices.length;
  30350. var ti = types[i], tj = types[j];
  30351. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30352. if (ti !== BACK)
  30353. f.push(vi);
  30354. if (ti !== FRONT)
  30355. b.push(ti !== BACK ? vi.clone() : vi);
  30356. if ((ti | tj) === SPANNING) {
  30357. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30358. var v = vi.interpolate(vj, t);
  30359. f.push(v);
  30360. b.push(v.clone());
  30361. }
  30362. }
  30363. var poly;
  30364. if (f.length >= 3) {
  30365. poly = new Polygon(f, polygon.shared);
  30366. if (poly.plane)
  30367. front.push(poly);
  30368. }
  30369. if (b.length >= 3) {
  30370. poly = new Polygon(b, polygon.shared);
  30371. if (poly.plane)
  30372. back.push(poly);
  30373. }
  30374. break;
  30375. }
  30376. };
  30377. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30378. // point is on the plane.
  30379. Plane.EPSILON = 1e-5;
  30380. return Plane;
  30381. })();
  30382. // # class Polygon
  30383. // Represents a convex polygon. The vertices used to initialize a polygon must
  30384. // be coplanar and form a convex loop.
  30385. //
  30386. // Each convex polygon has a `shared` property, which is shared between all
  30387. // polygons that are clones of each other or were split from the same polygon.
  30388. // This can be used to define per-polygon properties (such as surface color).
  30389. var Polygon = (function () {
  30390. function Polygon(vertices, shared) {
  30391. this.vertices = vertices;
  30392. this.shared = shared;
  30393. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30394. }
  30395. Polygon.prototype.clone = function () {
  30396. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30397. return new Polygon(vertices, this.shared);
  30398. };
  30399. Polygon.prototype.flip = function () {
  30400. this.vertices.reverse().map(function (v) { v.flip(); });
  30401. this.plane.flip();
  30402. };
  30403. return Polygon;
  30404. })();
  30405. // # class Node
  30406. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30407. // by picking a polygon to split along. That polygon (and all other coplanar
  30408. // polygons) are added directly to that node and the other polygons are added to
  30409. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30410. // no distinction between internal and leaf nodes.
  30411. var Node = (function () {
  30412. function Node(polygons) {
  30413. this.plane = null;
  30414. this.front = null;
  30415. this.back = null;
  30416. this.polygons = [];
  30417. if (polygons) {
  30418. this.build(polygons);
  30419. }
  30420. }
  30421. Node.prototype.clone = function () {
  30422. var node = new Node();
  30423. node.plane = this.plane && this.plane.clone();
  30424. node.front = this.front && this.front.clone();
  30425. node.back = this.back && this.back.clone();
  30426. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30427. return node;
  30428. };
  30429. // Convert solid space to empty space and empty space to solid space.
  30430. Node.prototype.invert = function () {
  30431. for (var i = 0; i < this.polygons.length; i++) {
  30432. this.polygons[i].flip();
  30433. }
  30434. if (this.plane) {
  30435. this.plane.flip();
  30436. }
  30437. if (this.front) {
  30438. this.front.invert();
  30439. }
  30440. if (this.back) {
  30441. this.back.invert();
  30442. }
  30443. var temp = this.front;
  30444. this.front = this.back;
  30445. this.back = temp;
  30446. };
  30447. // Recursively remove all polygons in `polygons` that are inside this BSP
  30448. // tree.
  30449. Node.prototype.clipPolygons = function (polygons) {
  30450. if (!this.plane)
  30451. return polygons.slice();
  30452. var front = [], back = [];
  30453. for (var i = 0; i < polygons.length; i++) {
  30454. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30455. }
  30456. if (this.front) {
  30457. front = this.front.clipPolygons(front);
  30458. }
  30459. if (this.back) {
  30460. back = this.back.clipPolygons(back);
  30461. }
  30462. else {
  30463. back = [];
  30464. }
  30465. return front.concat(back);
  30466. };
  30467. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30468. // `bsp`.
  30469. Node.prototype.clipTo = function (bsp) {
  30470. this.polygons = bsp.clipPolygons(this.polygons);
  30471. if (this.front)
  30472. this.front.clipTo(bsp);
  30473. if (this.back)
  30474. this.back.clipTo(bsp);
  30475. };
  30476. // Return a list of all polygons in this BSP tree.
  30477. Node.prototype.allPolygons = function () {
  30478. var polygons = this.polygons.slice();
  30479. if (this.front)
  30480. polygons = polygons.concat(this.front.allPolygons());
  30481. if (this.back)
  30482. polygons = polygons.concat(this.back.allPolygons());
  30483. return polygons;
  30484. };
  30485. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30486. // new polygons are filtered down to the bottom of the tree and become new
  30487. // nodes there. Each set of polygons is partitioned using the first polygon
  30488. // (no heuristic is used to pick a good split).
  30489. Node.prototype.build = function (polygons) {
  30490. if (!polygons.length)
  30491. return;
  30492. if (!this.plane)
  30493. this.plane = polygons[0].plane.clone();
  30494. var front = [], back = [];
  30495. for (var i = 0; i < polygons.length; i++) {
  30496. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30497. }
  30498. if (front.length) {
  30499. if (!this.front)
  30500. this.front = new Node();
  30501. this.front.build(front);
  30502. }
  30503. if (back.length) {
  30504. if (!this.back)
  30505. this.back = new Node();
  30506. this.back.build(back);
  30507. }
  30508. };
  30509. return Node;
  30510. })();
  30511. var CSG = (function () {
  30512. function CSG() {
  30513. this.polygons = new Array();
  30514. }
  30515. // Convert BABYLON.Mesh to BABYLON.CSG
  30516. CSG.FromMesh = function (mesh) {
  30517. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30518. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30519. if (mesh instanceof BABYLON.Mesh) {
  30520. mesh.computeWorldMatrix(true);
  30521. matrix = mesh.getWorldMatrix();
  30522. meshPosition = mesh.position.clone();
  30523. meshRotation = mesh.rotation.clone();
  30524. if (mesh.rotationQuaternion) {
  30525. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30526. }
  30527. meshScaling = mesh.scaling.clone();
  30528. }
  30529. else {
  30530. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30531. }
  30532. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30533. var subMeshes = mesh.subMeshes;
  30534. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30535. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30536. vertices = [];
  30537. for (var j = 0; j < 3; j++) {
  30538. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30539. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30540. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30541. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30542. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30543. vertex = new Vertex(position, normal, uv);
  30544. vertices.push(vertex);
  30545. }
  30546. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30547. // To handle the case of degenerated triangle
  30548. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30549. if (polygon.plane)
  30550. polygons.push(polygon);
  30551. }
  30552. }
  30553. var csg = CSG.FromPolygons(polygons);
  30554. csg.matrix = matrix;
  30555. csg.position = meshPosition;
  30556. csg.rotation = meshRotation;
  30557. csg.scaling = meshScaling;
  30558. csg.rotationQuaternion = meshRotationQuaternion;
  30559. currentCSGMeshId++;
  30560. return csg;
  30561. };
  30562. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30563. CSG.FromPolygons = function (polygons) {
  30564. var csg = new CSG();
  30565. csg.polygons = polygons;
  30566. return csg;
  30567. };
  30568. CSG.prototype.clone = function () {
  30569. var csg = new CSG();
  30570. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30571. csg.copyTransformAttributes(this);
  30572. return csg;
  30573. };
  30574. CSG.prototype.toPolygons = function () {
  30575. return this.polygons;
  30576. };
  30577. CSG.prototype.union = function (csg) {
  30578. var a = new Node(this.clone().polygons);
  30579. var b = new Node(csg.clone().polygons);
  30580. a.clipTo(b);
  30581. b.clipTo(a);
  30582. b.invert();
  30583. b.clipTo(a);
  30584. b.invert();
  30585. a.build(b.allPolygons());
  30586. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30587. };
  30588. CSG.prototype.unionInPlace = function (csg) {
  30589. var a = new Node(this.polygons);
  30590. var b = new Node(csg.polygons);
  30591. a.clipTo(b);
  30592. b.clipTo(a);
  30593. b.invert();
  30594. b.clipTo(a);
  30595. b.invert();
  30596. a.build(b.allPolygons());
  30597. this.polygons = a.allPolygons();
  30598. };
  30599. CSG.prototype.subtract = function (csg) {
  30600. var a = new Node(this.clone().polygons);
  30601. var b = new Node(csg.clone().polygons);
  30602. a.invert();
  30603. a.clipTo(b);
  30604. b.clipTo(a);
  30605. b.invert();
  30606. b.clipTo(a);
  30607. b.invert();
  30608. a.build(b.allPolygons());
  30609. a.invert();
  30610. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30611. };
  30612. CSG.prototype.subtractInPlace = function (csg) {
  30613. var a = new Node(this.polygons);
  30614. var b = new Node(csg.polygons);
  30615. a.invert();
  30616. a.clipTo(b);
  30617. b.clipTo(a);
  30618. b.invert();
  30619. b.clipTo(a);
  30620. b.invert();
  30621. a.build(b.allPolygons());
  30622. a.invert();
  30623. this.polygons = a.allPolygons();
  30624. };
  30625. CSG.prototype.intersect = function (csg) {
  30626. var a = new Node(this.clone().polygons);
  30627. var b = new Node(csg.clone().polygons);
  30628. a.invert();
  30629. b.clipTo(a);
  30630. b.invert();
  30631. a.clipTo(b);
  30632. b.clipTo(a);
  30633. a.build(b.allPolygons());
  30634. a.invert();
  30635. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30636. };
  30637. CSG.prototype.intersectInPlace = function (csg) {
  30638. var a = new Node(this.polygons);
  30639. var b = new Node(csg.polygons);
  30640. a.invert();
  30641. b.clipTo(a);
  30642. b.invert();
  30643. a.clipTo(b);
  30644. b.clipTo(a);
  30645. a.build(b.allPolygons());
  30646. a.invert();
  30647. this.polygons = a.allPolygons();
  30648. };
  30649. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30650. // not modified.
  30651. CSG.prototype.inverse = function () {
  30652. var csg = this.clone();
  30653. csg.inverseInPlace();
  30654. return csg;
  30655. };
  30656. CSG.prototype.inverseInPlace = function () {
  30657. this.polygons.map(function (p) { p.flip(); });
  30658. };
  30659. // This is used to keep meshes transformations so they can be restored
  30660. // when we build back a Babylon Mesh
  30661. // NB : All CSG operations are performed in world coordinates
  30662. CSG.prototype.copyTransformAttributes = function (csg) {
  30663. this.matrix = csg.matrix;
  30664. this.position = csg.position;
  30665. this.rotation = csg.rotation;
  30666. this.scaling = csg.scaling;
  30667. this.rotationQuaternion = csg.rotationQuaternion;
  30668. return this;
  30669. };
  30670. // Build Raw mesh from CSG
  30671. // Coordinates here are in world space
  30672. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30673. var matrix = this.matrix.clone();
  30674. matrix.invert();
  30675. 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;
  30676. if (keepSubMeshes) {
  30677. // Sort Polygons, since subMeshes are indices range
  30678. polygons.sort(function (a, b) {
  30679. if (a.shared.meshId === b.shared.meshId) {
  30680. return a.shared.subMeshId - b.shared.subMeshId;
  30681. }
  30682. else {
  30683. return a.shared.meshId - b.shared.meshId;
  30684. }
  30685. });
  30686. }
  30687. for (var i = 0, il = polygons.length; i < il; i++) {
  30688. polygon = polygons[i];
  30689. // Building SubMeshes
  30690. if (!subMesh_dict[polygon.shared.meshId]) {
  30691. subMesh_dict[polygon.shared.meshId] = {};
  30692. }
  30693. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30694. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30695. indexStart: +Infinity,
  30696. indexEnd: -Infinity,
  30697. materialIndex: polygon.shared.materialIndex
  30698. };
  30699. }
  30700. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30701. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30702. polygonIndices[0] = 0;
  30703. polygonIndices[1] = j - 1;
  30704. polygonIndices[2] = j;
  30705. for (var k = 0; k < 3; k++) {
  30706. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30707. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30708. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30709. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30710. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30711. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30712. // Check if 2 points can be merged
  30713. if (!(typeof vertex_idx !== 'undefined' &&
  30714. normals[vertex_idx * 3] === localNormal.x &&
  30715. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30716. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30717. uvs[vertex_idx * 2] === uv.x &&
  30718. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30719. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30720. uvs.push(uv.x, uv.y);
  30721. normals.push(normal.x, normal.y, normal.z);
  30722. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30723. }
  30724. indices.push(vertex_idx);
  30725. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30726. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30727. currentIndex++;
  30728. }
  30729. }
  30730. }
  30731. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30732. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30733. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30734. mesh.setIndices(indices);
  30735. if (keepSubMeshes) {
  30736. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30737. var materialIndexOffset = 0, materialMaxIndex;
  30738. mesh.subMeshes = new Array();
  30739. for (var m in subMesh_dict) {
  30740. materialMaxIndex = -1;
  30741. for (var sm in subMesh_dict[m]) {
  30742. subMesh_obj = subMesh_dict[m][sm];
  30743. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30744. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30745. }
  30746. materialIndexOffset += ++materialMaxIndex;
  30747. }
  30748. }
  30749. return mesh;
  30750. };
  30751. // Build Mesh from CSG taking material and transforms into account
  30752. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30753. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30754. mesh.material = material;
  30755. mesh.position.copyFrom(this.position);
  30756. mesh.rotation.copyFrom(this.rotation);
  30757. if (this.rotationQuaternion) {
  30758. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30759. }
  30760. mesh.scaling.copyFrom(this.scaling);
  30761. mesh.computeWorldMatrix(true);
  30762. return mesh;
  30763. };
  30764. return CSG;
  30765. })();
  30766. BABYLON.CSG = CSG;
  30767. })(BABYLON || (BABYLON = {}));
  30768. var BABYLON;
  30769. (function (BABYLON) {
  30770. var VRDistortionCorrectionPostProcess = (function (_super) {
  30771. __extends(VRDistortionCorrectionPostProcess, _super);
  30772. //ANY
  30773. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30774. var _this = this;
  30775. _super.call(this, name, "vrDistortionCorrection", [
  30776. 'LensCenter',
  30777. 'Scale',
  30778. 'ScaleIn',
  30779. 'HmdWarpParam'
  30780. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30781. this._isRightEye = isRightEye;
  30782. this._distortionFactors = vrMetrics.distortionK;
  30783. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30784. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30785. this.onSizeChanged = function () {
  30786. _this.aspectRatio = _this.width * .5 / _this.height;
  30787. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30788. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30789. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30790. };
  30791. this.onApply = function (effect) {
  30792. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30793. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30794. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30795. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30796. };
  30797. }
  30798. return VRDistortionCorrectionPostProcess;
  30799. })(BABYLON.PostProcess);
  30800. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30801. })(BABYLON || (BABYLON = {}));
  30802. // Mainly based on these 2 articles :
  30803. // 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
  30804. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30805. var BABYLON;
  30806. (function (BABYLON) {
  30807. (function (JoystickAxis) {
  30808. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30809. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30810. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30811. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30812. var JoystickAxis = BABYLON.JoystickAxis;
  30813. var VirtualJoystick = (function () {
  30814. function VirtualJoystick(leftJoystick) {
  30815. var _this = this;
  30816. if (leftJoystick) {
  30817. this._leftJoystick = true;
  30818. }
  30819. else {
  30820. this._leftJoystick = false;
  30821. }
  30822. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30823. VirtualJoystick._globalJoystickIndex++;
  30824. // By default left & right arrow keys are moving the X
  30825. // and up & down keys are moving the Y
  30826. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30827. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30828. this.reverseLeftRight = false;
  30829. this.reverseUpDown = false;
  30830. // collections of pointers
  30831. this._touches = new BABYLON.SmartCollection();
  30832. this.deltaPosition = BABYLON.Vector3.Zero();
  30833. this._joystickSensibility = 25;
  30834. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30835. this._rotationSpeed = 25;
  30836. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30837. this._rotateOnAxisRelativeToMesh = false;
  30838. this._onResize = function (evt) {
  30839. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30840. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30841. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30842. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30843. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30844. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30845. };
  30846. // injecting a canvas element on top of the canvas 3D game
  30847. if (!VirtualJoystick.vjCanvas) {
  30848. window.addEventListener("resize", this._onResize, false);
  30849. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30850. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30851. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30852. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30853. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30854. VirtualJoystick.vjCanvas.style.width = "100%";
  30855. VirtualJoystick.vjCanvas.style.height = "100%";
  30856. VirtualJoystick.vjCanvas.style.position = "absolute";
  30857. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30858. VirtualJoystick.vjCanvas.style.top = "0px";
  30859. VirtualJoystick.vjCanvas.style.left = "0px";
  30860. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30861. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30862. // Support for jQuery PEP polyfill
  30863. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30864. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30865. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30866. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30867. document.body.appendChild(VirtualJoystick.vjCanvas);
  30868. }
  30869. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30870. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30871. this.pressed = false;
  30872. // default joystick color
  30873. this._joystickColor = "cyan";
  30874. this._joystickPointerID = -1;
  30875. // current joystick position
  30876. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30877. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30878. // origin joystick position
  30879. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30880. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30881. this._onPointerDownHandlerRef = function (evt) {
  30882. _this._onPointerDown(evt);
  30883. };
  30884. this._onPointerMoveHandlerRef = function (evt) {
  30885. _this._onPointerMove(evt);
  30886. };
  30887. this._onPointerOutHandlerRef = function (evt) {
  30888. _this._onPointerUp(evt);
  30889. };
  30890. this._onPointerUpHandlerRef = function (evt) {
  30891. _this._onPointerUp(evt);
  30892. };
  30893. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30894. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30895. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30896. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30897. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30898. evt.preventDefault(); // Disables system menu
  30899. }, false);
  30900. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30901. }
  30902. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30903. this._joystickSensibility = newJoystickSensibility;
  30904. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30905. };
  30906. VirtualJoystick.prototype._onPointerDown = function (e) {
  30907. var positionOnScreenCondition;
  30908. e.preventDefault();
  30909. if (this._leftJoystick === true) {
  30910. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30911. }
  30912. else {
  30913. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30914. }
  30915. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30916. // First contact will be dedicated to the virtual joystick
  30917. this._joystickPointerID = e.pointerId;
  30918. this._joystickPointerStartPos.x = e.clientX;
  30919. this._joystickPointerStartPos.y = e.clientY;
  30920. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30921. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30922. this._deltaJoystickVector.x = 0;
  30923. this._deltaJoystickVector.y = 0;
  30924. this.pressed = true;
  30925. this._touches.add(e.pointerId.toString(), e);
  30926. }
  30927. else {
  30928. // You can only trigger the action buttons with a joystick declared
  30929. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30930. this._action();
  30931. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30932. }
  30933. }
  30934. };
  30935. VirtualJoystick.prototype._onPointerMove = function (e) {
  30936. // If the current pointer is the one associated to the joystick (first touch contact)
  30937. if (this._joystickPointerID == e.pointerId) {
  30938. this._joystickPointerPos.x = e.clientX;
  30939. this._joystickPointerPos.y = e.clientY;
  30940. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30941. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30942. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30943. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30944. switch (this._axisTargetedByLeftAndRight) {
  30945. case JoystickAxis.X:
  30946. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30947. break;
  30948. case JoystickAxis.Y:
  30949. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30950. break;
  30951. case JoystickAxis.Z:
  30952. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30953. break;
  30954. }
  30955. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30956. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30957. switch (this._axisTargetedByUpAndDown) {
  30958. case JoystickAxis.X:
  30959. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30960. break;
  30961. case JoystickAxis.Y:
  30962. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30963. break;
  30964. case JoystickAxis.Z:
  30965. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30966. break;
  30967. }
  30968. }
  30969. else {
  30970. if (this._touches.item(e.pointerId.toString())) {
  30971. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30972. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30973. }
  30974. }
  30975. };
  30976. VirtualJoystick.prototype._onPointerUp = function (e) {
  30977. if (this._joystickPointerID == e.pointerId) {
  30978. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30979. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30980. this._joystickPointerID = -1;
  30981. this.pressed = false;
  30982. }
  30983. else {
  30984. var touch = this._touches.item(e.pointerId.toString());
  30985. if (touch) {
  30986. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30987. }
  30988. }
  30989. this._deltaJoystickVector.x = 0;
  30990. this._deltaJoystickVector.y = 0;
  30991. this._touches.remove(e.pointerId.toString());
  30992. };
  30993. /**
  30994. * Change the color of the virtual joystick
  30995. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30996. */
  30997. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30998. this._joystickColor = newColor;
  30999. };
  31000. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31001. this._action = action;
  31002. };
  31003. // Define which axis you'd like to control for left & right
  31004. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31005. switch (axis) {
  31006. case JoystickAxis.X:
  31007. case JoystickAxis.Y:
  31008. case JoystickAxis.Z:
  31009. this._axisTargetedByLeftAndRight = axis;
  31010. break;
  31011. default:
  31012. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31013. break;
  31014. }
  31015. };
  31016. // Define which axis you'd like to control for up & down
  31017. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31018. switch (axis) {
  31019. case JoystickAxis.X:
  31020. case JoystickAxis.Y:
  31021. case JoystickAxis.Z:
  31022. this._axisTargetedByUpAndDown = axis;
  31023. break;
  31024. default:
  31025. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31026. break;
  31027. }
  31028. };
  31029. VirtualJoystick.prototype._clearCanvas = function () {
  31030. if (this._leftJoystick) {
  31031. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31032. }
  31033. else {
  31034. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31035. }
  31036. };
  31037. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31038. var _this = this;
  31039. if (this.pressed) {
  31040. this._touches.forEach(function (touch) {
  31041. if (touch.pointerId === _this._joystickPointerID) {
  31042. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31043. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31044. VirtualJoystick.vjCanvasContext.beginPath();
  31045. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31046. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31047. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31048. VirtualJoystick.vjCanvasContext.stroke();
  31049. VirtualJoystick.vjCanvasContext.closePath();
  31050. VirtualJoystick.vjCanvasContext.beginPath();
  31051. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31052. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31053. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31054. VirtualJoystick.vjCanvasContext.stroke();
  31055. VirtualJoystick.vjCanvasContext.closePath();
  31056. VirtualJoystick.vjCanvasContext.beginPath();
  31057. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31058. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31059. VirtualJoystick.vjCanvasContext.stroke();
  31060. VirtualJoystick.vjCanvasContext.closePath();
  31061. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31062. }
  31063. else {
  31064. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31065. VirtualJoystick.vjCanvasContext.beginPath();
  31066. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31067. VirtualJoystick.vjCanvasContext.beginPath();
  31068. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31069. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31070. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31071. VirtualJoystick.vjCanvasContext.stroke();
  31072. VirtualJoystick.vjCanvasContext.closePath();
  31073. touch.prevX = touch.x;
  31074. touch.prevY = touch.y;
  31075. }
  31076. ;
  31077. });
  31078. }
  31079. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31080. };
  31081. VirtualJoystick.prototype.releaseCanvas = function () {
  31082. if (VirtualJoystick.vjCanvas) {
  31083. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31084. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31085. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31086. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31087. window.removeEventListener("resize", this._onResize);
  31088. document.body.removeChild(VirtualJoystick.vjCanvas);
  31089. VirtualJoystick.vjCanvas = null;
  31090. }
  31091. };
  31092. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31093. VirtualJoystick._globalJoystickIndex = 0;
  31094. return VirtualJoystick;
  31095. })();
  31096. BABYLON.VirtualJoystick = VirtualJoystick;
  31097. })(BABYLON || (BABYLON = {}));
  31098. var BABYLON;
  31099. (function (BABYLON) {
  31100. // We're mainly based on the logic defined into the FreeCamera code
  31101. var VirtualJoysticksCamera = (function (_super) {
  31102. __extends(VirtualJoysticksCamera, _super);
  31103. function VirtualJoysticksCamera(name, position, scene) {
  31104. _super.call(this, name, position, scene);
  31105. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31106. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31107. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31108. this._leftjoystick.setJoystickSensibility(0.15);
  31109. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31110. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31111. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31112. this._rightjoystick.reverseUpDown = true;
  31113. this._rightjoystick.setJoystickSensibility(0.05);
  31114. this._rightjoystick.setJoystickColor("yellow");
  31115. }
  31116. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31117. return this._leftjoystick;
  31118. };
  31119. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31120. return this._rightjoystick;
  31121. };
  31122. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31123. var speed = this._computeLocalCameraSpeed() * 50;
  31124. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31125. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31126. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31127. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31128. if (!this._leftjoystick.pressed) {
  31129. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31130. }
  31131. if (!this._rightjoystick.pressed) {
  31132. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31133. }
  31134. _super.prototype._checkInputs.call(this);
  31135. };
  31136. VirtualJoysticksCamera.prototype.dispose = function () {
  31137. this._leftjoystick.releaseCanvas();
  31138. _super.prototype.dispose.call(this);
  31139. };
  31140. return VirtualJoysticksCamera;
  31141. })(BABYLON.FreeCamera);
  31142. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31143. })(BABYLON || (BABYLON = {}));
  31144. var BABYLON;
  31145. (function (BABYLON) {
  31146. var AnaglyphPostProcess = (function (_super) {
  31147. __extends(AnaglyphPostProcess, _super);
  31148. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31149. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31150. }
  31151. return AnaglyphPostProcess;
  31152. })(BABYLON.PostProcess);
  31153. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31154. })(BABYLON || (BABYLON = {}));
  31155. var BABYLON;
  31156. (function (BABYLON) {
  31157. var OutlineRenderer = (function () {
  31158. function OutlineRenderer(scene) {
  31159. this._scene = scene;
  31160. }
  31161. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31162. var _this = this;
  31163. if (useOverlay === void 0) { useOverlay = false; }
  31164. var scene = this._scene;
  31165. var engine = this._scene.getEngine();
  31166. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31167. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31168. return;
  31169. }
  31170. var mesh = subMesh.getRenderingMesh();
  31171. var material = subMesh.getMaterial();
  31172. engine.enableEffect(this._effect);
  31173. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31174. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31175. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31176. // Bones
  31177. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31178. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31179. }
  31180. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31181. // Alpha test
  31182. if (material && material.needAlphaTesting()) {
  31183. var alphaTexture = material.getAlphaTestTexture();
  31184. this._effect.setTexture("diffuseSampler", alphaTexture);
  31185. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31186. }
  31187. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31188. };
  31189. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31190. var defines = [];
  31191. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31192. var mesh = subMesh.getMesh();
  31193. var material = subMesh.getMaterial();
  31194. // Alpha test
  31195. if (material && material.needAlphaTesting()) {
  31196. defines.push("#define ALPHATEST");
  31197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31198. attribs.push(BABYLON.VertexBuffer.UVKind);
  31199. defines.push("#define UV1");
  31200. }
  31201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31203. defines.push("#define UV2");
  31204. }
  31205. }
  31206. // Bones
  31207. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31210. if (mesh.numBoneInfluencers > 4) {
  31211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31213. }
  31214. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31215. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31216. }
  31217. else {
  31218. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31219. }
  31220. // Instances
  31221. if (useInstances) {
  31222. defines.push("#define INSTANCES");
  31223. attribs.push("world0");
  31224. attribs.push("world1");
  31225. attribs.push("world2");
  31226. attribs.push("world3");
  31227. }
  31228. // Get correct effect
  31229. var join = defines.join("\n");
  31230. if (this._cachedDefines !== join) {
  31231. this._cachedDefines = join;
  31232. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31233. }
  31234. return this._effect.isReady();
  31235. };
  31236. return OutlineRenderer;
  31237. })();
  31238. BABYLON.OutlineRenderer = OutlineRenderer;
  31239. })(BABYLON || (BABYLON = {}));
  31240. var BABYLON;
  31241. (function (BABYLON) {
  31242. var MeshAssetTask = (function () {
  31243. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31244. this.name = name;
  31245. this.meshesNames = meshesNames;
  31246. this.rootUrl = rootUrl;
  31247. this.sceneFilename = sceneFilename;
  31248. this.isCompleted = false;
  31249. }
  31250. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31251. var _this = this;
  31252. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31253. _this.loadedMeshes = meshes;
  31254. _this.loadedParticleSystems = particleSystems;
  31255. _this.loadedSkeletons = skeletons;
  31256. _this.isCompleted = true;
  31257. if (_this.onSuccess) {
  31258. _this.onSuccess(_this);
  31259. }
  31260. onSuccess();
  31261. }, null, function () {
  31262. if (_this.onError) {
  31263. _this.onError(_this);
  31264. }
  31265. onError();
  31266. });
  31267. };
  31268. return MeshAssetTask;
  31269. })();
  31270. BABYLON.MeshAssetTask = MeshAssetTask;
  31271. var TextFileAssetTask = (function () {
  31272. function TextFileAssetTask(name, url) {
  31273. this.name = name;
  31274. this.url = url;
  31275. this.isCompleted = false;
  31276. }
  31277. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31278. var _this = this;
  31279. BABYLON.Tools.LoadFile(this.url, function (data) {
  31280. _this.text = data;
  31281. _this.isCompleted = true;
  31282. if (_this.onSuccess) {
  31283. _this.onSuccess(_this);
  31284. }
  31285. onSuccess();
  31286. }, null, scene.database, false, function () {
  31287. if (_this.onError) {
  31288. _this.onError(_this);
  31289. }
  31290. onError();
  31291. });
  31292. };
  31293. return TextFileAssetTask;
  31294. })();
  31295. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31296. var BinaryFileAssetTask = (function () {
  31297. function BinaryFileAssetTask(name, url) {
  31298. this.name = name;
  31299. this.url = url;
  31300. this.isCompleted = false;
  31301. }
  31302. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31303. var _this = this;
  31304. BABYLON.Tools.LoadFile(this.url, function (data) {
  31305. _this.data = data;
  31306. _this.isCompleted = true;
  31307. if (_this.onSuccess) {
  31308. _this.onSuccess(_this);
  31309. }
  31310. onSuccess();
  31311. }, null, scene.database, true, function () {
  31312. if (_this.onError) {
  31313. _this.onError(_this);
  31314. }
  31315. onError();
  31316. });
  31317. };
  31318. return BinaryFileAssetTask;
  31319. })();
  31320. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31321. var ImageAssetTask = (function () {
  31322. function ImageAssetTask(name, url) {
  31323. this.name = name;
  31324. this.url = url;
  31325. this.isCompleted = false;
  31326. }
  31327. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31328. var _this = this;
  31329. var img = new Image();
  31330. img.onload = function () {
  31331. _this.image = img;
  31332. _this.isCompleted = true;
  31333. if (_this.onSuccess) {
  31334. _this.onSuccess(_this);
  31335. }
  31336. onSuccess();
  31337. };
  31338. img.onerror = function () {
  31339. if (_this.onError) {
  31340. _this.onError(_this);
  31341. }
  31342. onError();
  31343. };
  31344. img.src = this.url;
  31345. };
  31346. return ImageAssetTask;
  31347. })();
  31348. BABYLON.ImageAssetTask = ImageAssetTask;
  31349. var TextureAssetTask = (function () {
  31350. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31352. this.name = name;
  31353. this.url = url;
  31354. this.noMipmap = noMipmap;
  31355. this.invertY = invertY;
  31356. this.samplingMode = samplingMode;
  31357. this.isCompleted = false;
  31358. }
  31359. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31360. var _this = this;
  31361. var onload = function () {
  31362. _this.isCompleted = true;
  31363. if (_this.onSuccess) {
  31364. _this.onSuccess(_this);
  31365. }
  31366. onSuccess();
  31367. };
  31368. var onerror = function () {
  31369. if (_this.onError) {
  31370. _this.onError(_this);
  31371. }
  31372. onError();
  31373. };
  31374. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31375. };
  31376. return TextureAssetTask;
  31377. })();
  31378. BABYLON.TextureAssetTask = TextureAssetTask;
  31379. var AssetsManager = (function () {
  31380. function AssetsManager(scene) {
  31381. this._tasks = new Array();
  31382. this._waitingTasksCount = 0;
  31383. this.useDefaultLoadingScreen = true;
  31384. this._scene = scene;
  31385. }
  31386. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31387. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31388. this._tasks.push(task);
  31389. return task;
  31390. };
  31391. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31392. var task = new TextFileAssetTask(taskName, url);
  31393. this._tasks.push(task);
  31394. return task;
  31395. };
  31396. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31397. var task = new BinaryFileAssetTask(taskName, url);
  31398. this._tasks.push(task);
  31399. return task;
  31400. };
  31401. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31402. var task = new ImageAssetTask(taskName, url);
  31403. this._tasks.push(task);
  31404. return task;
  31405. };
  31406. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31408. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31409. this._tasks.push(task);
  31410. return task;
  31411. };
  31412. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31413. this._waitingTasksCount--;
  31414. if (this._waitingTasksCount === 0) {
  31415. if (this.onFinish) {
  31416. this.onFinish(this._tasks);
  31417. }
  31418. this._scene.getEngine().hideLoadingUI();
  31419. }
  31420. };
  31421. AssetsManager.prototype._runTask = function (task) {
  31422. var _this = this;
  31423. task.run(this._scene, function () {
  31424. if (_this.onTaskSuccess) {
  31425. _this.onTaskSuccess(task);
  31426. }
  31427. _this._decreaseWaitingTasksCount();
  31428. }, function () {
  31429. if (_this.onTaskError) {
  31430. _this.onTaskError(task);
  31431. }
  31432. _this._decreaseWaitingTasksCount();
  31433. });
  31434. };
  31435. AssetsManager.prototype.reset = function () {
  31436. this._tasks = new Array();
  31437. return this;
  31438. };
  31439. AssetsManager.prototype.load = function () {
  31440. this._waitingTasksCount = this._tasks.length;
  31441. if (this._waitingTasksCount === 0) {
  31442. if (this.onFinish) {
  31443. this.onFinish(this._tasks);
  31444. }
  31445. return this;
  31446. }
  31447. if (this.useDefaultLoadingScreen) {
  31448. this._scene.getEngine().displayLoadingUI();
  31449. }
  31450. for (var index = 0; index < this._tasks.length; index++) {
  31451. var task = this._tasks[index];
  31452. this._runTask(task);
  31453. }
  31454. return this;
  31455. };
  31456. return AssetsManager;
  31457. })();
  31458. BABYLON.AssetsManager = AssetsManager;
  31459. })(BABYLON || (BABYLON = {}));
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. var VRDeviceOrientationFreeCamera = (function (_super) {
  31463. __extends(VRDeviceOrientationFreeCamera, _super);
  31464. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31465. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31466. _super.call(this, name, position, scene);
  31467. this._alpha = 0;
  31468. this._beta = 0;
  31469. this._gamma = 0;
  31470. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31471. metrics.compensateDistortion = compensateDistortion;
  31472. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31473. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31474. }
  31475. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31476. this._alpha = +evt.alpha | 0;
  31477. this._beta = +evt.beta | 0;
  31478. this._gamma = +evt.gamma | 0;
  31479. if (this._gamma < 0) {
  31480. this._gamma = 90 + this._gamma;
  31481. }
  31482. else {
  31483. // Incline it in the correct angle.
  31484. this._gamma = 270 - this._gamma;
  31485. }
  31486. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31487. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31488. this.rotation.z = this._beta / 180.0 * Math.PI;
  31489. };
  31490. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31491. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31492. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31493. };
  31494. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31495. _super.prototype.detachControl.call(this, element);
  31496. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31497. };
  31498. return VRDeviceOrientationFreeCamera;
  31499. })(BABYLON.FreeCamera);
  31500. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31501. })(BABYLON || (BABYLON = {}));
  31502. var BABYLON;
  31503. (function (BABYLON) {
  31504. var WebVRFreeCamera = (function (_super) {
  31505. __extends(WebVRFreeCamera, _super);
  31506. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31507. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31508. _super.call(this, name, position, scene);
  31509. this._hmdDevice = null;
  31510. this._sensorDevice = null;
  31511. this._cacheState = null;
  31512. this._cacheQuaternion = new BABYLON.Quaternion();
  31513. this._cacheRotation = BABYLON.Vector3.Zero();
  31514. this._vrEnabled = false;
  31515. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31516. metrics.compensateDistortion = compensateDistortion;
  31517. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31518. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31519. }
  31520. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31521. var size = devices.length;
  31522. var i = 0;
  31523. // Reset devices.
  31524. this._sensorDevice = null;
  31525. this._hmdDevice = null;
  31526. // Search for a HmdDevice.
  31527. while (i < size && this._hmdDevice === null) {
  31528. if (devices[i] instanceof HMDVRDevice) {
  31529. this._hmdDevice = devices[i];
  31530. }
  31531. i++;
  31532. }
  31533. i = 0;
  31534. while (i < size && this._sensorDevice === null) {
  31535. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31536. this._sensorDevice = devices[i];
  31537. }
  31538. i++;
  31539. }
  31540. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31541. };
  31542. WebVRFreeCamera.prototype._checkInputs = function () {
  31543. if (this._vrEnabled) {
  31544. this._cacheState = this._sensorDevice.getState();
  31545. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31546. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31547. this.rotation.x = -this._cacheRotation.z;
  31548. this.rotation.y = -this._cacheRotation.y;
  31549. this.rotation.z = this._cacheRotation.x;
  31550. }
  31551. _super.prototype._checkInputs.call(this);
  31552. };
  31553. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31554. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31555. if (navigator.getVRDevices) {
  31556. navigator.getVRDevices().then(this._getWebVRDevices);
  31557. }
  31558. else if (navigator.mozGetVRDevices) {
  31559. navigator.mozGetVRDevices(this._getWebVRDevices);
  31560. }
  31561. };
  31562. WebVRFreeCamera.prototype.detachControl = function (element) {
  31563. _super.prototype.detachControl.call(this, element);
  31564. this._vrEnabled = false;
  31565. };
  31566. return WebVRFreeCamera;
  31567. })(BABYLON.FreeCamera);
  31568. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31569. })(BABYLON || (BABYLON = {}));
  31570. var BABYLON;
  31571. (function (BABYLON) {
  31572. // Standard optimizations
  31573. var SceneOptimization = (function () {
  31574. function SceneOptimization(priority) {
  31575. if (priority === void 0) { priority = 0; }
  31576. this.priority = priority;
  31577. this.apply = function (scene) {
  31578. return true; // Return true if everything that can be done was applied
  31579. };
  31580. }
  31581. return SceneOptimization;
  31582. })();
  31583. BABYLON.SceneOptimization = SceneOptimization;
  31584. var TextureOptimization = (function (_super) {
  31585. __extends(TextureOptimization, _super);
  31586. function TextureOptimization(priority, maximumSize) {
  31587. var _this = this;
  31588. if (priority === void 0) { priority = 0; }
  31589. if (maximumSize === void 0) { maximumSize = 1024; }
  31590. _super.call(this, priority);
  31591. this.priority = priority;
  31592. this.maximumSize = maximumSize;
  31593. this.apply = function (scene) {
  31594. var allDone = true;
  31595. for (var index = 0; index < scene.textures.length; index++) {
  31596. var texture = scene.textures[index];
  31597. if (!texture.canRescale) {
  31598. continue;
  31599. }
  31600. var currentSize = texture.getSize();
  31601. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31602. if (maxDimension > _this.maximumSize) {
  31603. texture.scale(0.5);
  31604. allDone = false;
  31605. }
  31606. }
  31607. return allDone;
  31608. };
  31609. }
  31610. return TextureOptimization;
  31611. })(SceneOptimization);
  31612. BABYLON.TextureOptimization = TextureOptimization;
  31613. var HardwareScalingOptimization = (function (_super) {
  31614. __extends(HardwareScalingOptimization, _super);
  31615. function HardwareScalingOptimization(priority, maximumScale) {
  31616. var _this = this;
  31617. if (priority === void 0) { priority = 0; }
  31618. if (maximumScale === void 0) { maximumScale = 2; }
  31619. _super.call(this, priority);
  31620. this.priority = priority;
  31621. this.maximumScale = maximumScale;
  31622. this._currentScale = 1;
  31623. this.apply = function (scene) {
  31624. _this._currentScale++;
  31625. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31626. return _this._currentScale >= _this.maximumScale;
  31627. };
  31628. }
  31629. return HardwareScalingOptimization;
  31630. })(SceneOptimization);
  31631. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31632. var ShadowsOptimization = (function (_super) {
  31633. __extends(ShadowsOptimization, _super);
  31634. function ShadowsOptimization() {
  31635. _super.apply(this, arguments);
  31636. this.apply = function (scene) {
  31637. scene.shadowsEnabled = false;
  31638. return true;
  31639. };
  31640. }
  31641. return ShadowsOptimization;
  31642. })(SceneOptimization);
  31643. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31644. var PostProcessesOptimization = (function (_super) {
  31645. __extends(PostProcessesOptimization, _super);
  31646. function PostProcessesOptimization() {
  31647. _super.apply(this, arguments);
  31648. this.apply = function (scene) {
  31649. scene.postProcessesEnabled = false;
  31650. return true;
  31651. };
  31652. }
  31653. return PostProcessesOptimization;
  31654. })(SceneOptimization);
  31655. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31656. var LensFlaresOptimization = (function (_super) {
  31657. __extends(LensFlaresOptimization, _super);
  31658. function LensFlaresOptimization() {
  31659. _super.apply(this, arguments);
  31660. this.apply = function (scene) {
  31661. scene.lensFlaresEnabled = false;
  31662. return true;
  31663. };
  31664. }
  31665. return LensFlaresOptimization;
  31666. })(SceneOptimization);
  31667. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31668. var ParticlesOptimization = (function (_super) {
  31669. __extends(ParticlesOptimization, _super);
  31670. function ParticlesOptimization() {
  31671. _super.apply(this, arguments);
  31672. this.apply = function (scene) {
  31673. scene.particlesEnabled = false;
  31674. return true;
  31675. };
  31676. }
  31677. return ParticlesOptimization;
  31678. })(SceneOptimization);
  31679. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31680. var RenderTargetsOptimization = (function (_super) {
  31681. __extends(RenderTargetsOptimization, _super);
  31682. function RenderTargetsOptimization() {
  31683. _super.apply(this, arguments);
  31684. this.apply = function (scene) {
  31685. scene.renderTargetsEnabled = false;
  31686. return true;
  31687. };
  31688. }
  31689. return RenderTargetsOptimization;
  31690. })(SceneOptimization);
  31691. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31692. var MergeMeshesOptimization = (function (_super) {
  31693. __extends(MergeMeshesOptimization, _super);
  31694. function MergeMeshesOptimization() {
  31695. var _this = this;
  31696. _super.apply(this, arguments);
  31697. this._canBeMerged = function (abstractMesh) {
  31698. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31699. return false;
  31700. }
  31701. var mesh = abstractMesh;
  31702. if (!mesh.isVisible || !mesh.isEnabled()) {
  31703. return false;
  31704. }
  31705. if (mesh.instances.length > 0) {
  31706. return false;
  31707. }
  31708. if (mesh.skeleton || mesh.hasLODLevels) {
  31709. return false;
  31710. }
  31711. if (mesh.parent) {
  31712. return false;
  31713. }
  31714. return true;
  31715. };
  31716. this.apply = function (scene, updateSelectionTree) {
  31717. var globalPool = scene.meshes.slice(0);
  31718. var globalLength = globalPool.length;
  31719. for (var index = 0; index < globalLength; index++) {
  31720. var currentPool = new Array();
  31721. var current = globalPool[index];
  31722. // Checks
  31723. if (!_this._canBeMerged(current)) {
  31724. continue;
  31725. }
  31726. currentPool.push(current);
  31727. // Find compatible meshes
  31728. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31729. var otherMesh = globalPool[subIndex];
  31730. if (!_this._canBeMerged(otherMesh)) {
  31731. continue;
  31732. }
  31733. if (otherMesh.material !== current.material) {
  31734. continue;
  31735. }
  31736. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31737. continue;
  31738. }
  31739. currentPool.push(otherMesh);
  31740. globalLength--;
  31741. globalPool.splice(subIndex, 1);
  31742. subIndex--;
  31743. }
  31744. if (currentPool.length < 2) {
  31745. continue;
  31746. }
  31747. // Merge meshes
  31748. BABYLON.Mesh.MergeMeshes(currentPool);
  31749. }
  31750. if (updateSelectionTree != undefined) {
  31751. if (updateSelectionTree) {
  31752. scene.createOrUpdateSelectionOctree();
  31753. }
  31754. }
  31755. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31756. scene.createOrUpdateSelectionOctree();
  31757. }
  31758. return true;
  31759. };
  31760. }
  31761. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31762. get: function () {
  31763. return MergeMeshesOptimization._UpdateSelectionTree;
  31764. },
  31765. set: function (value) {
  31766. MergeMeshesOptimization._UpdateSelectionTree = value;
  31767. },
  31768. enumerable: true,
  31769. configurable: true
  31770. });
  31771. MergeMeshesOptimization._UpdateSelectionTree = false;
  31772. return MergeMeshesOptimization;
  31773. })(SceneOptimization);
  31774. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31775. // Options
  31776. var SceneOptimizerOptions = (function () {
  31777. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31778. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31779. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31780. this.targetFrameRate = targetFrameRate;
  31781. this.trackerDuration = trackerDuration;
  31782. this.optimizations = new Array();
  31783. }
  31784. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31785. var result = new SceneOptimizerOptions(targetFrameRate);
  31786. var priority = 0;
  31787. result.optimizations.push(new MergeMeshesOptimization(priority));
  31788. result.optimizations.push(new ShadowsOptimization(priority));
  31789. result.optimizations.push(new LensFlaresOptimization(priority));
  31790. // Next priority
  31791. priority++;
  31792. result.optimizations.push(new PostProcessesOptimization(priority));
  31793. result.optimizations.push(new ParticlesOptimization(priority));
  31794. // Next priority
  31795. priority++;
  31796. result.optimizations.push(new TextureOptimization(priority, 1024));
  31797. return result;
  31798. };
  31799. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31800. var result = new SceneOptimizerOptions(targetFrameRate);
  31801. var priority = 0;
  31802. result.optimizations.push(new MergeMeshesOptimization(priority));
  31803. result.optimizations.push(new ShadowsOptimization(priority));
  31804. result.optimizations.push(new LensFlaresOptimization(priority));
  31805. // Next priority
  31806. priority++;
  31807. result.optimizations.push(new PostProcessesOptimization(priority));
  31808. result.optimizations.push(new ParticlesOptimization(priority));
  31809. // Next priority
  31810. priority++;
  31811. result.optimizations.push(new TextureOptimization(priority, 512));
  31812. // Next priority
  31813. priority++;
  31814. result.optimizations.push(new RenderTargetsOptimization(priority));
  31815. // Next priority
  31816. priority++;
  31817. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31818. return result;
  31819. };
  31820. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31821. var result = new SceneOptimizerOptions(targetFrameRate);
  31822. var priority = 0;
  31823. result.optimizations.push(new MergeMeshesOptimization(priority));
  31824. result.optimizations.push(new ShadowsOptimization(priority));
  31825. result.optimizations.push(new LensFlaresOptimization(priority));
  31826. // Next priority
  31827. priority++;
  31828. result.optimizations.push(new PostProcessesOptimization(priority));
  31829. result.optimizations.push(new ParticlesOptimization(priority));
  31830. // Next priority
  31831. priority++;
  31832. result.optimizations.push(new TextureOptimization(priority, 256));
  31833. // Next priority
  31834. priority++;
  31835. result.optimizations.push(new RenderTargetsOptimization(priority));
  31836. // Next priority
  31837. priority++;
  31838. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31839. return result;
  31840. };
  31841. return SceneOptimizerOptions;
  31842. })();
  31843. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31844. // Scene optimizer tool
  31845. var SceneOptimizer = (function () {
  31846. function SceneOptimizer() {
  31847. }
  31848. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31849. // TODO: add an epsilon
  31850. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31851. if (onSuccess) {
  31852. onSuccess();
  31853. }
  31854. return;
  31855. }
  31856. // Apply current level of optimizations
  31857. var allDone = true;
  31858. var noOptimizationApplied = true;
  31859. for (var index = 0; index < options.optimizations.length; index++) {
  31860. var optimization = options.optimizations[index];
  31861. if (optimization.priority === currentPriorityLevel) {
  31862. noOptimizationApplied = false;
  31863. allDone = allDone && optimization.apply(scene);
  31864. }
  31865. }
  31866. // If no optimization was applied, this is a failure :(
  31867. if (noOptimizationApplied) {
  31868. if (onFailure) {
  31869. onFailure();
  31870. }
  31871. return;
  31872. }
  31873. // If all optimizations were done, move to next level
  31874. if (allDone) {
  31875. currentPriorityLevel++;
  31876. }
  31877. // Let's the system running for a specific amount of time before checking FPS
  31878. scene.executeWhenReady(function () {
  31879. setTimeout(function () {
  31880. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31881. }, options.trackerDuration);
  31882. });
  31883. };
  31884. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31885. if (!options) {
  31886. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31887. }
  31888. // Let's the system running for a specific amount of time before checking FPS
  31889. scene.executeWhenReady(function () {
  31890. setTimeout(function () {
  31891. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31892. }, options.trackerDuration);
  31893. });
  31894. };
  31895. return SceneOptimizer;
  31896. })();
  31897. BABYLON.SceneOptimizer = SceneOptimizer;
  31898. })(BABYLON || (BABYLON = {}));
  31899. var BABYLON;
  31900. (function (BABYLON) {
  31901. var Internals;
  31902. (function (Internals) {
  31903. var MeshLODLevel = (function () {
  31904. function MeshLODLevel(distance, mesh) {
  31905. this.distance = distance;
  31906. this.mesh = mesh;
  31907. }
  31908. return MeshLODLevel;
  31909. })();
  31910. Internals.MeshLODLevel = MeshLODLevel;
  31911. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31912. })(BABYLON || (BABYLON = {}));
  31913. var BABYLON;
  31914. (function (BABYLON) {
  31915. var RawTexture = (function (_super) {
  31916. __extends(RawTexture, _super);
  31917. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31918. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31919. if (invertY === void 0) { invertY = false; }
  31920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31921. _super.call(this, null, scene, !generateMipMaps, invertY);
  31922. this.format = format;
  31923. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31924. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31925. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31926. }
  31927. RawTexture.prototype.update = function (data) {
  31928. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31929. };
  31930. // Statics
  31931. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31932. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31933. if (invertY === void 0) { invertY = false; }
  31934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31935. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31936. };
  31937. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31938. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31939. if (invertY === void 0) { invertY = false; }
  31940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31941. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31942. };
  31943. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31945. if (invertY === void 0) { invertY = false; }
  31946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31947. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31948. };
  31949. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31950. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31951. if (invertY === void 0) { invertY = false; }
  31952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31953. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31954. };
  31955. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31957. if (invertY === void 0) { invertY = false; }
  31958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31959. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31960. };
  31961. return RawTexture;
  31962. })(BABYLON.Texture);
  31963. BABYLON.RawTexture = RawTexture;
  31964. })(BABYLON || (BABYLON = {}));
  31965. var BABYLON;
  31966. (function (BABYLON) {
  31967. var IndexedVector2 = (function (_super) {
  31968. __extends(IndexedVector2, _super);
  31969. function IndexedVector2(original, index) {
  31970. _super.call(this, original.x, original.y);
  31971. this.index = index;
  31972. }
  31973. return IndexedVector2;
  31974. })(BABYLON.Vector2);
  31975. var PolygonPoints = (function () {
  31976. function PolygonPoints() {
  31977. this.elements = new Array();
  31978. }
  31979. PolygonPoints.prototype.add = function (originalPoints) {
  31980. var _this = this;
  31981. var result = new Array();
  31982. originalPoints.forEach(function (point) {
  31983. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31984. var newPoint = new IndexedVector2(point, _this.elements.length);
  31985. result.push(newPoint);
  31986. _this.elements.push(newPoint);
  31987. }
  31988. });
  31989. return result;
  31990. };
  31991. PolygonPoints.prototype.computeBounds = function () {
  31992. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31993. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31994. this.elements.forEach(function (point) {
  31995. // x
  31996. if (point.x < lmin.x) {
  31997. lmin.x = point.x;
  31998. }
  31999. else if (point.x > lmax.x) {
  32000. lmax.x = point.x;
  32001. }
  32002. // y
  32003. if (point.y < lmin.y) {
  32004. lmin.y = point.y;
  32005. }
  32006. else if (point.y > lmax.y) {
  32007. lmax.y = point.y;
  32008. }
  32009. });
  32010. return {
  32011. min: lmin,
  32012. max: lmax,
  32013. width: lmax.x - lmin.x,
  32014. height: lmax.y - lmin.y
  32015. };
  32016. };
  32017. return PolygonPoints;
  32018. })();
  32019. var Polygon = (function () {
  32020. function Polygon() {
  32021. }
  32022. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32023. return [
  32024. new BABYLON.Vector2(xmin, ymin),
  32025. new BABYLON.Vector2(xmax, ymin),
  32026. new BABYLON.Vector2(xmax, ymax),
  32027. new BABYLON.Vector2(xmin, ymax)
  32028. ];
  32029. };
  32030. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32031. if (cx === void 0) { cx = 0; }
  32032. if (cy === void 0) { cy = 0; }
  32033. if (numberOfSides === void 0) { numberOfSides = 32; }
  32034. var result = new Array();
  32035. var angle = 0;
  32036. var increment = (Math.PI * 2) / numberOfSides;
  32037. for (var i = 0; i < numberOfSides; i++) {
  32038. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32039. angle -= increment;
  32040. }
  32041. return result;
  32042. };
  32043. Polygon.Parse = function (input) {
  32044. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32045. var i, result = [];
  32046. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32047. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32048. }
  32049. return result;
  32050. };
  32051. Polygon.StartingAt = function (x, y) {
  32052. return BABYLON.Path2.StartingAt(x, y);
  32053. };
  32054. return Polygon;
  32055. })();
  32056. BABYLON.Polygon = Polygon;
  32057. var PolygonMeshBuilder = (function () {
  32058. function PolygonMeshBuilder(name, contours, scene) {
  32059. this._points = new PolygonPoints();
  32060. this._outlinepoints = new PolygonPoints();
  32061. this._holes = [];
  32062. if (!("poly2tri" in window)) {
  32063. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32064. }
  32065. this._name = name;
  32066. this._scene = scene;
  32067. var points;
  32068. if (contours instanceof BABYLON.Path2) {
  32069. points = contours.getPoints();
  32070. }
  32071. else {
  32072. points = contours;
  32073. }
  32074. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32075. this._outlinepoints.add(points);
  32076. }
  32077. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32078. this._swctx.addHole(this._points.add(hole));
  32079. var holepoints = new PolygonPoints();
  32080. holepoints.add(hole);
  32081. this._holes.push(holepoints);
  32082. return this;
  32083. };
  32084. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32085. var _this = this;
  32086. if (updatable === void 0) { updatable = false; }
  32087. var result = new BABYLON.Mesh(this._name, this._scene);
  32088. var normals = [];
  32089. var positions = [];
  32090. var uvs = [];
  32091. var bounds = this._points.computeBounds();
  32092. this._points.elements.forEach(function (p) {
  32093. normals.push(0, 1.0, 0);
  32094. positions.push(p.x, 0, p.y);
  32095. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32096. });
  32097. var indices = [];
  32098. this._swctx.triangulate();
  32099. this._swctx.getTriangles().forEach(function (triangle) {
  32100. triangle.getPoints().forEach(function (point) {
  32101. indices.push(point.index);
  32102. });
  32103. });
  32104. if (depth > 0) {
  32105. var positionscount = (positions.length / 3); //get the current pointcount
  32106. this._points.elements.forEach(function (p) {
  32107. normals.push(0, -1.0, 0);
  32108. positions.push(p.x, -depth, p.y);
  32109. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32110. });
  32111. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32112. var p2;
  32113. var poscounter = 0;
  32114. this._swctx.getTriangles().forEach(function (triangle) {
  32115. triangle.getPoints().forEach(function (point) {
  32116. switch (poscounter) {
  32117. case 0:
  32118. p1 = point;
  32119. break;
  32120. case 1:
  32121. p2 = point;
  32122. break;
  32123. case 2:
  32124. indices.push(point.index + positionscount);
  32125. indices.push(p2.index + positionscount);
  32126. indices.push(p1.index + positionscount);
  32127. poscounter = -1;
  32128. break;
  32129. }
  32130. poscounter++;
  32131. //indices.push((<IndexedVector2>point).index + positionscount);
  32132. });
  32133. });
  32134. //Add the sides
  32135. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32136. this._holes.forEach(function (hole) {
  32137. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32138. });
  32139. }
  32140. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32141. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32142. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32143. result.setIndices(indices);
  32144. return result;
  32145. };
  32146. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32147. var StartIndex = positions.length / 3;
  32148. var ulength = 0;
  32149. for (var i = 0; i < points.elements.length; i++) {
  32150. var p = points.elements[i];
  32151. var p1;
  32152. if ((i + 1) > points.elements.length - 1) {
  32153. p1 = points.elements[0];
  32154. }
  32155. else {
  32156. p1 = points.elements[i + 1];
  32157. }
  32158. positions.push(p.x, 0, p.y);
  32159. positions.push(p.x, -depth, p.y);
  32160. positions.push(p1.x, 0, p1.y);
  32161. positions.push(p1.x, -depth, p1.y);
  32162. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32163. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32164. var v3 = v2.subtract(v1);
  32165. var v4 = new BABYLON.Vector3(0, 1, 0);
  32166. var vn = BABYLON.Vector3.Cross(v3, v4);
  32167. vn = vn.normalize();
  32168. uvs.push(ulength / bounds.width, 0);
  32169. uvs.push(ulength / bounds.width, 1);
  32170. ulength += v3.length();
  32171. uvs.push((ulength / bounds.width), 0);
  32172. uvs.push((ulength / bounds.width), 1);
  32173. if (!flip) {
  32174. normals.push(-vn.x, -vn.y, -vn.z);
  32175. normals.push(-vn.x, -vn.y, -vn.z);
  32176. normals.push(-vn.x, -vn.y, -vn.z);
  32177. normals.push(-vn.x, -vn.y, -vn.z);
  32178. indices.push(StartIndex);
  32179. indices.push(StartIndex + 1);
  32180. indices.push(StartIndex + 2);
  32181. indices.push(StartIndex + 1);
  32182. indices.push(StartIndex + 3);
  32183. indices.push(StartIndex + 2);
  32184. }
  32185. else {
  32186. normals.push(vn.x, vn.y, vn.z);
  32187. normals.push(vn.x, vn.y, vn.z);
  32188. normals.push(vn.x, vn.y, vn.z);
  32189. normals.push(vn.x, vn.y, vn.z);
  32190. indices.push(StartIndex);
  32191. indices.push(StartIndex + 2);
  32192. indices.push(StartIndex + 1);
  32193. indices.push(StartIndex + 1);
  32194. indices.push(StartIndex + 2);
  32195. indices.push(StartIndex + 3);
  32196. }
  32197. StartIndex += 4;
  32198. }
  32199. ;
  32200. };
  32201. return PolygonMeshBuilder;
  32202. })();
  32203. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32204. })(BABYLON || (BABYLON = {}));
  32205. var BABYLON;
  32206. (function (BABYLON) {
  32207. var Octree = (function () {
  32208. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32209. if (maxDepth === void 0) { maxDepth = 2; }
  32210. this.maxDepth = maxDepth;
  32211. this.dynamicContent = new Array();
  32212. this._maxBlockCapacity = maxBlockCapacity || 64;
  32213. this._selectionContent = new BABYLON.SmartArray(1024);
  32214. this._creationFunc = creationFunc;
  32215. }
  32216. // Methods
  32217. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32218. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32219. };
  32220. Octree.prototype.addMesh = function (entry) {
  32221. for (var index = 0; index < this.blocks.length; index++) {
  32222. var block = this.blocks[index];
  32223. block.addEntry(entry);
  32224. }
  32225. };
  32226. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32227. this._selectionContent.reset();
  32228. for (var index = 0; index < this.blocks.length; index++) {
  32229. var block = this.blocks[index];
  32230. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32231. }
  32232. if (allowDuplicate) {
  32233. this._selectionContent.concat(this.dynamicContent);
  32234. }
  32235. else {
  32236. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32237. }
  32238. return this._selectionContent;
  32239. };
  32240. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32241. this._selectionContent.reset();
  32242. for (var index = 0; index < this.blocks.length; index++) {
  32243. var block = this.blocks[index];
  32244. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32245. }
  32246. if (allowDuplicate) {
  32247. this._selectionContent.concat(this.dynamicContent);
  32248. }
  32249. else {
  32250. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32251. }
  32252. return this._selectionContent;
  32253. };
  32254. Octree.prototype.intersectsRay = function (ray) {
  32255. this._selectionContent.reset();
  32256. for (var index = 0; index < this.blocks.length; index++) {
  32257. var block = this.blocks[index];
  32258. block.intersectsRay(ray, this._selectionContent);
  32259. }
  32260. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32261. return this._selectionContent;
  32262. };
  32263. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32264. target.blocks = new Array();
  32265. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32266. // Segmenting space
  32267. for (var x = 0; x < 2; x++) {
  32268. for (var y = 0; y < 2; y++) {
  32269. for (var z = 0; z < 2; z++) {
  32270. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32271. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32272. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32273. block.addEntries(entries);
  32274. target.blocks.push(block);
  32275. }
  32276. }
  32277. }
  32278. };
  32279. Octree.CreationFuncForMeshes = function (entry, block) {
  32280. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32281. block.entries.push(entry);
  32282. }
  32283. };
  32284. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32285. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32286. block.entries.push(entry);
  32287. }
  32288. };
  32289. return Octree;
  32290. })();
  32291. BABYLON.Octree = Octree;
  32292. })(BABYLON || (BABYLON = {}));
  32293. var BABYLON;
  32294. (function (BABYLON) {
  32295. var OctreeBlock = (function () {
  32296. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32297. this.entries = new Array();
  32298. this._boundingVectors = new Array();
  32299. this._capacity = capacity;
  32300. this._depth = depth;
  32301. this._maxDepth = maxDepth;
  32302. this._creationFunc = creationFunc;
  32303. this._minPoint = minPoint;
  32304. this._maxPoint = maxPoint;
  32305. this._boundingVectors.push(minPoint.clone());
  32306. this._boundingVectors.push(maxPoint.clone());
  32307. this._boundingVectors.push(minPoint.clone());
  32308. this._boundingVectors[2].x = maxPoint.x;
  32309. this._boundingVectors.push(minPoint.clone());
  32310. this._boundingVectors[3].y = maxPoint.y;
  32311. this._boundingVectors.push(minPoint.clone());
  32312. this._boundingVectors[4].z = maxPoint.z;
  32313. this._boundingVectors.push(maxPoint.clone());
  32314. this._boundingVectors[5].z = minPoint.z;
  32315. this._boundingVectors.push(maxPoint.clone());
  32316. this._boundingVectors[6].x = minPoint.x;
  32317. this._boundingVectors.push(maxPoint.clone());
  32318. this._boundingVectors[7].y = minPoint.y;
  32319. }
  32320. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32321. // Property
  32322. get: function () {
  32323. return this._capacity;
  32324. },
  32325. enumerable: true,
  32326. configurable: true
  32327. });
  32328. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32329. get: function () {
  32330. return this._minPoint;
  32331. },
  32332. enumerable: true,
  32333. configurable: true
  32334. });
  32335. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32336. get: function () {
  32337. return this._maxPoint;
  32338. },
  32339. enumerable: true,
  32340. configurable: true
  32341. });
  32342. // Methods
  32343. OctreeBlock.prototype.addEntry = function (entry) {
  32344. if (this.blocks) {
  32345. for (var index = 0; index < this.blocks.length; index++) {
  32346. var block = this.blocks[index];
  32347. block.addEntry(entry);
  32348. }
  32349. return;
  32350. }
  32351. this._creationFunc(entry, this);
  32352. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32353. this.createInnerBlocks();
  32354. }
  32355. };
  32356. OctreeBlock.prototype.addEntries = function (entries) {
  32357. for (var index = 0; index < entries.length; index++) {
  32358. var mesh = entries[index];
  32359. this.addEntry(mesh);
  32360. }
  32361. };
  32362. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32363. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32364. if (this.blocks) {
  32365. for (var index = 0; index < this.blocks.length; index++) {
  32366. var block = this.blocks[index];
  32367. block.select(frustumPlanes, selection, allowDuplicate);
  32368. }
  32369. return;
  32370. }
  32371. if (allowDuplicate) {
  32372. selection.concat(this.entries);
  32373. }
  32374. else {
  32375. selection.concatWithNoDuplicate(this.entries);
  32376. }
  32377. }
  32378. };
  32379. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32380. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32381. if (this.blocks) {
  32382. for (var index = 0; index < this.blocks.length; index++) {
  32383. var block = this.blocks[index];
  32384. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32385. }
  32386. return;
  32387. }
  32388. if (allowDuplicate) {
  32389. selection.concat(this.entries);
  32390. }
  32391. else {
  32392. selection.concatWithNoDuplicate(this.entries);
  32393. }
  32394. }
  32395. };
  32396. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32397. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32398. if (this.blocks) {
  32399. for (var index = 0; index < this.blocks.length; index++) {
  32400. var block = this.blocks[index];
  32401. block.intersectsRay(ray, selection);
  32402. }
  32403. return;
  32404. }
  32405. selection.concatWithNoDuplicate(this.entries);
  32406. }
  32407. };
  32408. OctreeBlock.prototype.createInnerBlocks = function () {
  32409. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32410. };
  32411. return OctreeBlock;
  32412. })();
  32413. BABYLON.OctreeBlock = OctreeBlock;
  32414. })(BABYLON || (BABYLON = {}));
  32415. var BABYLON;
  32416. (function (BABYLON) {
  32417. var BlurPostProcess = (function (_super) {
  32418. __extends(BlurPostProcess, _super);
  32419. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32420. var _this = this;
  32421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32422. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32423. this.direction = direction;
  32424. this.blurWidth = blurWidth;
  32425. this.onApply = function (effect) {
  32426. effect.setFloat2("screenSize", _this.width, _this.height);
  32427. effect.setVector2("direction", _this.direction);
  32428. effect.setFloat("blurWidth", _this.blurWidth);
  32429. };
  32430. }
  32431. return BlurPostProcess;
  32432. })(BABYLON.PostProcess);
  32433. BABYLON.BlurPostProcess = BlurPostProcess;
  32434. })(BABYLON || (BABYLON = {}));
  32435. var BABYLON;
  32436. (function (BABYLON) {
  32437. var RefractionPostProcess = (function (_super) {
  32438. __extends(RefractionPostProcess, _super);
  32439. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32440. var _this = this;
  32441. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32442. this.color = color;
  32443. this.depth = depth;
  32444. this.colorLevel = colorLevel;
  32445. this.onActivate = function (cam) {
  32446. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32447. };
  32448. this.onApply = function (effect) {
  32449. effect.setColor3("baseColor", _this.color);
  32450. effect.setFloat("depth", _this.depth);
  32451. effect.setFloat("colorLevel", _this.colorLevel);
  32452. effect.setTexture("refractionSampler", _this._refRexture);
  32453. };
  32454. }
  32455. // Methods
  32456. RefractionPostProcess.prototype.dispose = function (camera) {
  32457. if (this._refRexture) {
  32458. this._refRexture.dispose();
  32459. }
  32460. _super.prototype.dispose.call(this, camera);
  32461. };
  32462. return RefractionPostProcess;
  32463. })(BABYLON.PostProcess);
  32464. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32465. })(BABYLON || (BABYLON = {}));
  32466. var BABYLON;
  32467. (function (BABYLON) {
  32468. var BlackAndWhitePostProcess = (function (_super) {
  32469. __extends(BlackAndWhitePostProcess, _super);
  32470. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32471. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32472. }
  32473. return BlackAndWhitePostProcess;
  32474. })(BABYLON.PostProcess);
  32475. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32476. })(BABYLON || (BABYLON = {}));
  32477. var BABYLON;
  32478. (function (BABYLON) {
  32479. var ConvolutionPostProcess = (function (_super) {
  32480. __extends(ConvolutionPostProcess, _super);
  32481. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32482. var _this = this;
  32483. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32484. this.kernel = kernel;
  32485. this.onApply = function (effect) {
  32486. effect.setFloat2("screenSize", _this.width, _this.height);
  32487. effect.setArray("kernel", _this.kernel);
  32488. };
  32489. }
  32490. // Statics
  32491. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32492. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32493. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32494. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32495. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32496. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32497. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32498. return ConvolutionPostProcess;
  32499. })(BABYLON.PostProcess);
  32500. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32501. })(BABYLON || (BABYLON = {}));
  32502. var BABYLON;
  32503. (function (BABYLON) {
  32504. var FilterPostProcess = (function (_super) {
  32505. __extends(FilterPostProcess, _super);
  32506. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32507. var _this = this;
  32508. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32509. this.kernelMatrix = kernelMatrix;
  32510. this.onApply = function (effect) {
  32511. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32512. };
  32513. }
  32514. return FilterPostProcess;
  32515. })(BABYLON.PostProcess);
  32516. BABYLON.FilterPostProcess = FilterPostProcess;
  32517. })(BABYLON || (BABYLON = {}));
  32518. var BABYLON;
  32519. (function (BABYLON) {
  32520. var FxaaPostProcess = (function (_super) {
  32521. __extends(FxaaPostProcess, _super);
  32522. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32523. var _this = this;
  32524. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32525. this.onSizeChanged = function () {
  32526. _this.texelWidth = 1.0 / _this.width;
  32527. _this.texelHeight = 1.0 / _this.height;
  32528. };
  32529. this.onApply = function (effect) {
  32530. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32531. };
  32532. }
  32533. return FxaaPostProcess;
  32534. })(BABYLON.PostProcess);
  32535. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32536. })(BABYLON || (BABYLON = {}));
  32537. var BABYLON;
  32538. (function (BABYLON) {
  32539. var StereoscopicInterlacePostProcess = (function (_super) {
  32540. __extends(StereoscopicInterlacePostProcess, _super);
  32541. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32542. var _this = this;
  32543. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32544. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32545. this.onSizeChanged = function () {
  32546. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32547. };
  32548. this.onApply = function (effect) {
  32549. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32550. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32551. };
  32552. }
  32553. return StereoscopicInterlacePostProcess;
  32554. })(BABYLON.PostProcess);
  32555. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32556. })(BABYLON || (BABYLON = {}));
  32557. var BABYLON;
  32558. (function (BABYLON) {
  32559. var LensFlare = (function () {
  32560. function LensFlare(size, position, color, imgUrl, system) {
  32561. this.size = size;
  32562. this.position = position;
  32563. this.dispose = function () {
  32564. if (this.texture) {
  32565. this.texture.dispose();
  32566. }
  32567. // Remove from scene
  32568. var index = this._system.lensFlares.indexOf(this);
  32569. this._system.lensFlares.splice(index, 1);
  32570. };
  32571. this.color = color || new BABYLON.Color3(1, 1, 1);
  32572. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32573. this._system = system;
  32574. system.lensFlares.push(this);
  32575. }
  32576. return LensFlare;
  32577. })();
  32578. BABYLON.LensFlare = LensFlare;
  32579. })(BABYLON || (BABYLON = {}));
  32580. var BABYLON;
  32581. (function (BABYLON) {
  32582. var LensFlareSystem = (function () {
  32583. function LensFlareSystem(name, emitter, scene) {
  32584. this.name = name;
  32585. this.lensFlares = new Array();
  32586. this.borderLimit = 300;
  32587. this.layerMask = 0x0FFFFFFF;
  32588. this._vertexDeclaration = [2];
  32589. this._vertexStrideSize = 2 * 4;
  32590. this._isEnabled = true;
  32591. this._scene = scene;
  32592. this._emitter = emitter;
  32593. scene.lensFlareSystems.push(this);
  32594. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32595. // VBO
  32596. var vertices = [];
  32597. vertices.push(1, 1);
  32598. vertices.push(-1, 1);
  32599. vertices.push(-1, -1);
  32600. vertices.push(1, -1);
  32601. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32602. // Indices
  32603. var indices = [];
  32604. indices.push(0);
  32605. indices.push(1);
  32606. indices.push(2);
  32607. indices.push(0);
  32608. indices.push(2);
  32609. indices.push(3);
  32610. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32611. // Effects
  32612. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32613. }
  32614. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32615. get: function () {
  32616. return this._isEnabled;
  32617. },
  32618. set: function (value) {
  32619. this._isEnabled = value;
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. LensFlareSystem.prototype.getScene = function () {
  32625. return this._scene;
  32626. };
  32627. LensFlareSystem.prototype.getEmitter = function () {
  32628. return this._emitter;
  32629. };
  32630. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32631. this._emitter = newEmitter;
  32632. };
  32633. LensFlareSystem.prototype.getEmitterPosition = function () {
  32634. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32635. };
  32636. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32637. var position = this.getEmitterPosition();
  32638. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32639. this._positionX = position.x;
  32640. this._positionY = position.y;
  32641. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32642. if (position.z > 0) {
  32643. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32644. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32645. return true;
  32646. }
  32647. }
  32648. return false;
  32649. };
  32650. LensFlareSystem.prototype._isVisible = function () {
  32651. if (!this._isEnabled) {
  32652. return false;
  32653. }
  32654. var emitterPosition = this.getEmitterPosition();
  32655. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32656. var distance = direction.length();
  32657. direction.normalize();
  32658. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32659. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32660. return !pickInfo.hit || pickInfo.distance > distance;
  32661. };
  32662. LensFlareSystem.prototype.render = function () {
  32663. if (!this._effect.isReady())
  32664. return false;
  32665. var engine = this._scene.getEngine();
  32666. var viewport = this._scene.activeCamera.viewport;
  32667. var globalViewport = viewport.toGlobal(engine);
  32668. // Position
  32669. if (!this.computeEffectivePosition(globalViewport)) {
  32670. return false;
  32671. }
  32672. // Visibility
  32673. if (!this._isVisible()) {
  32674. return false;
  32675. }
  32676. // Intensity
  32677. var awayX;
  32678. var awayY;
  32679. if (this._positionX < this.borderLimit + globalViewport.x) {
  32680. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32681. }
  32682. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32683. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32684. }
  32685. else {
  32686. awayX = 0;
  32687. }
  32688. if (this._positionY < this.borderLimit + globalViewport.y) {
  32689. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32690. }
  32691. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32692. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32693. }
  32694. else {
  32695. awayY = 0;
  32696. }
  32697. var away = (awayX > awayY) ? awayX : awayY;
  32698. if (away > this.borderLimit) {
  32699. away = this.borderLimit;
  32700. }
  32701. var intensity = 1.0 - (away / this.borderLimit);
  32702. if (intensity < 0) {
  32703. return false;
  32704. }
  32705. if (intensity > 1.0) {
  32706. intensity = 1.0;
  32707. }
  32708. // Position
  32709. var centerX = globalViewport.x + globalViewport.width / 2;
  32710. var centerY = globalViewport.y + globalViewport.height / 2;
  32711. var distX = centerX - this._positionX;
  32712. var distY = centerY - this._positionY;
  32713. // Effects
  32714. engine.enableEffect(this._effect);
  32715. engine.setState(false);
  32716. engine.setDepthBuffer(false);
  32717. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32718. // VBOs
  32719. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32720. // Flares
  32721. for (var index = 0; index < this.lensFlares.length; index++) {
  32722. var flare = this.lensFlares[index];
  32723. var x = centerX - (distX * flare.position);
  32724. var y = centerY - (distY * flare.position);
  32725. var cw = flare.size;
  32726. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32727. var cx = 2 * (x / globalViewport.width) - 1.0;
  32728. var cy = 1.0 - 2 * (y / globalViewport.height);
  32729. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32730. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32731. // Texture
  32732. this._effect.setTexture("textureSampler", flare.texture);
  32733. // Color
  32734. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32735. // Draw order
  32736. engine.draw(true, 0, 6);
  32737. }
  32738. engine.setDepthBuffer(true);
  32739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32740. return true;
  32741. };
  32742. LensFlareSystem.prototype.dispose = function () {
  32743. if (this._vertexBuffer) {
  32744. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32745. this._vertexBuffer = null;
  32746. }
  32747. if (this._indexBuffer) {
  32748. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32749. this._indexBuffer = null;
  32750. }
  32751. while (this.lensFlares.length) {
  32752. this.lensFlares[0].dispose();
  32753. }
  32754. // Remove from scene
  32755. var index = this._scene.lensFlareSystems.indexOf(this);
  32756. this._scene.lensFlareSystems.splice(index, 1);
  32757. };
  32758. return LensFlareSystem;
  32759. })();
  32760. BABYLON.LensFlareSystem = LensFlareSystem;
  32761. })(BABYLON || (BABYLON = {}));
  32762. var BABYLON;
  32763. (function (BABYLON) {
  32764. // We're mainly based on the logic defined into the FreeCamera code
  32765. var DeviceOrientationCamera = (function (_super) {
  32766. __extends(DeviceOrientationCamera, _super);
  32767. function DeviceOrientationCamera(name, position, scene) {
  32768. var _this = this;
  32769. _super.call(this, name, position, scene);
  32770. this._offsetX = null;
  32771. this._offsetY = null;
  32772. this._orientationGamma = 0;
  32773. this._orientationBeta = 0;
  32774. this._initialOrientationGamma = 0;
  32775. this._initialOrientationBeta = 0;
  32776. this.angularSensibility = 10000.0;
  32777. this.moveSensibility = 50.0;
  32778. window.addEventListener("resize", function () {
  32779. _this._initialOrientationGamma = null;
  32780. }, false);
  32781. }
  32782. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32783. var _this = this;
  32784. if (this._attachedCanvas) {
  32785. return;
  32786. }
  32787. this._attachedCanvas = canvas;
  32788. if (!this._orientationChanged) {
  32789. this._orientationChanged = function (evt) {
  32790. if (!_this._initialOrientationGamma) {
  32791. _this._initialOrientationGamma = evt.gamma;
  32792. _this._initialOrientationBeta = evt.beta;
  32793. }
  32794. _this._orientationGamma = evt.gamma;
  32795. _this._orientationBeta = evt.beta;
  32796. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32797. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32798. };
  32799. }
  32800. window.addEventListener("deviceorientation", this._orientationChanged);
  32801. };
  32802. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32803. if (this._attachedCanvas != canvas) {
  32804. return;
  32805. }
  32806. window.removeEventListener("deviceorientation", this._orientationChanged);
  32807. this._attachedCanvas = null;
  32808. this._orientationGamma = 0;
  32809. this._orientationBeta = 0;
  32810. this._initialOrientationGamma = 0;
  32811. this._initialOrientationBeta = 0;
  32812. };
  32813. DeviceOrientationCamera.prototype._checkInputs = function () {
  32814. if (!this._offsetX) {
  32815. return;
  32816. }
  32817. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32818. var speed = this._computeLocalCameraSpeed();
  32819. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32820. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32821. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32822. _super.prototype._checkInputs.call(this);
  32823. };
  32824. return DeviceOrientationCamera;
  32825. })(BABYLON.FreeCamera);
  32826. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32827. })(BABYLON || (BABYLON = {}));
  32828. var BABYLON;
  32829. (function (BABYLON) {
  32830. var Gamepads = (function () {
  32831. function Gamepads(ongamedpadconnected) {
  32832. var _this = this;
  32833. this.babylonGamepads = [];
  32834. this.oneGamepadConnected = false;
  32835. this.isMonitoring = false;
  32836. this.gamepadEventSupported = 'GamepadEvent' in window;
  32837. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32838. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32839. 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=";
  32840. this._callbackGamepadConnected = ongamedpadconnected;
  32841. if (this.gamepadSupportAvailable) {
  32842. // Checking if the gamepad connected event is supported (like in Firefox)
  32843. if (this.gamepadEventSupported) {
  32844. window.addEventListener('gamepadconnected', function (evt) {
  32845. _this._onGamepadConnected(evt);
  32846. }, false);
  32847. window.addEventListener('gamepaddisconnected', function (evt) {
  32848. _this._onGamepadDisconnected(evt);
  32849. }, false);
  32850. }
  32851. else {
  32852. this._startMonitoringGamepads();
  32853. }
  32854. if (!this.oneGamepadConnected) {
  32855. this._insertGamepadDOMInstructions();
  32856. }
  32857. }
  32858. else {
  32859. this._insertGamepadDOMNotSupported();
  32860. }
  32861. }
  32862. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32863. Gamepads.gamepadDOMInfo = document.createElement("div");
  32864. var buttonAImage = document.createElement("img");
  32865. buttonAImage.src = this.buttonADataURL;
  32866. var spanMessage = document.createElement("span");
  32867. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32868. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32869. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32870. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32871. Gamepads.gamepadDOMInfo.style.width = "100%";
  32872. Gamepads.gamepadDOMInfo.style.height = "48px";
  32873. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32874. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32875. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32876. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32877. buttonAImage.style.position = "relative";
  32878. buttonAImage.style.bottom = "8px";
  32879. spanMessage.style.position = "relative";
  32880. spanMessage.style.fontSize = "32px";
  32881. spanMessage.style.bottom = "32px";
  32882. spanMessage.style.color = "green";
  32883. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32884. };
  32885. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32886. Gamepads.gamepadDOMInfo = document.createElement("div");
  32887. var spanMessage = document.createElement("span");
  32888. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32889. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32890. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32891. Gamepads.gamepadDOMInfo.style.width = "100%";
  32892. Gamepads.gamepadDOMInfo.style.height = "40px";
  32893. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32894. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32895. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32896. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32897. spanMessage.style.position = "relative";
  32898. spanMessage.style.fontSize = "32px";
  32899. spanMessage.style.color = "red";
  32900. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32901. };
  32902. Gamepads.prototype.dispose = function () {
  32903. if (Gamepads.gamepadDOMInfo) {
  32904. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32905. }
  32906. };
  32907. Gamepads.prototype._onGamepadConnected = function (evt) {
  32908. var newGamepad = this._addNewGamepad(evt.gamepad);
  32909. if (this._callbackGamepadConnected)
  32910. this._callbackGamepadConnected(newGamepad);
  32911. this._startMonitoringGamepads();
  32912. };
  32913. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32914. if (!this.oneGamepadConnected) {
  32915. this.oneGamepadConnected = true;
  32916. if (Gamepads.gamepadDOMInfo) {
  32917. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32918. Gamepads.gamepadDOMInfo = null;
  32919. }
  32920. }
  32921. var newGamepad;
  32922. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32923. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32924. }
  32925. else {
  32926. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32927. }
  32928. this.babylonGamepads.push(newGamepad);
  32929. return newGamepad;
  32930. };
  32931. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32932. // Remove the gamepad from the list of gamepads to monitor.
  32933. for (var i in this.babylonGamepads) {
  32934. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32935. this.babylonGamepads.splice(i, 1);
  32936. break;
  32937. }
  32938. }
  32939. // If no gamepads are left, stop the polling loop.
  32940. if (this.babylonGamepads.length == 0) {
  32941. this._stopMonitoringGamepads();
  32942. }
  32943. };
  32944. Gamepads.prototype._startMonitoringGamepads = function () {
  32945. if (!this.isMonitoring) {
  32946. this.isMonitoring = true;
  32947. this._checkGamepadsStatus();
  32948. }
  32949. };
  32950. Gamepads.prototype._stopMonitoringGamepads = function () {
  32951. this.isMonitoring = false;
  32952. };
  32953. Gamepads.prototype._checkGamepadsStatus = function () {
  32954. var _this = this;
  32955. // updating gamepad objects
  32956. this._updateGamepadObjects();
  32957. for (var i in this.babylonGamepads) {
  32958. this.babylonGamepads[i].update();
  32959. }
  32960. if (this.isMonitoring) {
  32961. if (window.requestAnimationFrame) {
  32962. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32963. }
  32964. else if (window.mozRequestAnimationFrame) {
  32965. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32966. }
  32967. else if (window.webkitRequestAnimationFrame) {
  32968. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32969. }
  32970. }
  32971. };
  32972. // This function is called only on Chrome, which does not yet support
  32973. // connection/disconnection events, but requires you to monitor
  32974. // an array for changes.
  32975. Gamepads.prototype._updateGamepadObjects = function () {
  32976. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32977. for (var i = 0; i < gamepads.length; i++) {
  32978. if (gamepads[i]) {
  32979. if (!(gamepads[i].index in this.babylonGamepads)) {
  32980. var newGamepad = this._addNewGamepad(gamepads[i]);
  32981. if (this._callbackGamepadConnected) {
  32982. this._callbackGamepadConnected(newGamepad);
  32983. }
  32984. }
  32985. else {
  32986. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32987. }
  32988. }
  32989. }
  32990. };
  32991. return Gamepads;
  32992. })();
  32993. BABYLON.Gamepads = Gamepads;
  32994. var StickValues = (function () {
  32995. function StickValues(x, y) {
  32996. this.x = x;
  32997. this.y = y;
  32998. }
  32999. return StickValues;
  33000. })();
  33001. BABYLON.StickValues = StickValues;
  33002. var Gamepad = (function () {
  33003. function Gamepad(id, index, browserGamepad) {
  33004. this.id = id;
  33005. this.index = index;
  33006. this.browserGamepad = browserGamepad;
  33007. if (this.browserGamepad.axes.length >= 2) {
  33008. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33009. }
  33010. if (this.browserGamepad.axes.length >= 4) {
  33011. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33012. }
  33013. }
  33014. Gamepad.prototype.onleftstickchanged = function (callback) {
  33015. this._onleftstickchanged = callback;
  33016. };
  33017. Gamepad.prototype.onrightstickchanged = function (callback) {
  33018. this._onrightstickchanged = callback;
  33019. };
  33020. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33021. get: function () {
  33022. return this._leftStick;
  33023. },
  33024. set: function (newValues) {
  33025. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33026. this._onleftstickchanged(newValues);
  33027. }
  33028. this._leftStick = newValues;
  33029. },
  33030. enumerable: true,
  33031. configurable: true
  33032. });
  33033. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33034. get: function () {
  33035. return this._rightStick;
  33036. },
  33037. set: function (newValues) {
  33038. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33039. this._onrightstickchanged(newValues);
  33040. }
  33041. this._rightStick = newValues;
  33042. },
  33043. enumerable: true,
  33044. configurable: true
  33045. });
  33046. Gamepad.prototype.update = function () {
  33047. if (this._leftStick) {
  33048. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33049. }
  33050. if (this._rightStick) {
  33051. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33052. }
  33053. };
  33054. return Gamepad;
  33055. })();
  33056. BABYLON.Gamepad = Gamepad;
  33057. var GenericPad = (function (_super) {
  33058. __extends(GenericPad, _super);
  33059. function GenericPad(id, index, gamepad) {
  33060. _super.call(this, id, index, gamepad);
  33061. this.id = id;
  33062. this.index = index;
  33063. this.gamepad = gamepad;
  33064. this._buttons = new Array(gamepad.buttons.length);
  33065. }
  33066. GenericPad.prototype.onbuttondown = function (callback) {
  33067. this._onbuttondown = callback;
  33068. };
  33069. GenericPad.prototype.onbuttonup = function (callback) {
  33070. this._onbuttonup = callback;
  33071. };
  33072. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33073. if (newValue !== currentValue) {
  33074. if (this._onbuttondown && newValue === 1) {
  33075. this._onbuttondown(buttonIndex);
  33076. }
  33077. if (this._onbuttonup && newValue === 0) {
  33078. this._onbuttonup(buttonIndex);
  33079. }
  33080. }
  33081. return newValue;
  33082. };
  33083. GenericPad.prototype.update = function () {
  33084. _super.prototype.update.call(this);
  33085. for (var index = 0; index < this._buttons.length; index++) {
  33086. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33087. }
  33088. };
  33089. return GenericPad;
  33090. })(Gamepad);
  33091. BABYLON.GenericPad = GenericPad;
  33092. (function (Xbox360Button) {
  33093. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33094. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33095. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33096. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33097. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33098. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33099. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33100. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33101. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33102. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33103. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33104. var Xbox360Button = BABYLON.Xbox360Button;
  33105. (function (Xbox360Dpad) {
  33106. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33107. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33108. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33109. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33110. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33111. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33112. var Xbox360Pad = (function (_super) {
  33113. __extends(Xbox360Pad, _super);
  33114. function Xbox360Pad() {
  33115. _super.apply(this, arguments);
  33116. this._leftTrigger = 0;
  33117. this._rightTrigger = 0;
  33118. this._buttonA = 0;
  33119. this._buttonB = 0;
  33120. this._buttonX = 0;
  33121. this._buttonY = 0;
  33122. this._buttonBack = 0;
  33123. this._buttonStart = 0;
  33124. this._buttonLB = 0;
  33125. this._buttonRB = 0;
  33126. this._buttonLeftStick = 0;
  33127. this._buttonRightStick = 0;
  33128. this._dPadUp = 0;
  33129. this._dPadDown = 0;
  33130. this._dPadLeft = 0;
  33131. this._dPadRight = 0;
  33132. }
  33133. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33134. this._onlefttriggerchanged = callback;
  33135. };
  33136. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33137. this._onrighttriggerchanged = callback;
  33138. };
  33139. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33140. get: function () {
  33141. return this._leftTrigger;
  33142. },
  33143. set: function (newValue) {
  33144. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33145. this._onlefttriggerchanged(newValue);
  33146. }
  33147. this._leftTrigger = newValue;
  33148. },
  33149. enumerable: true,
  33150. configurable: true
  33151. });
  33152. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33153. get: function () {
  33154. return this._rightTrigger;
  33155. },
  33156. set: function (newValue) {
  33157. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33158. this._onrighttriggerchanged(newValue);
  33159. }
  33160. this._rightTrigger = newValue;
  33161. },
  33162. enumerable: true,
  33163. configurable: true
  33164. });
  33165. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33166. this._onbuttondown = callback;
  33167. };
  33168. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33169. this._onbuttonup = callback;
  33170. };
  33171. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33172. this._ondpaddown = callback;
  33173. };
  33174. Xbox360Pad.prototype.ondpadup = function (callback) {
  33175. this._ondpadup = callback;
  33176. };
  33177. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33178. if (newValue !== currentValue) {
  33179. if (this._onbuttondown && newValue === 1) {
  33180. this._onbuttondown(buttonType);
  33181. }
  33182. if (this._onbuttonup && newValue === 0) {
  33183. this._onbuttonup(buttonType);
  33184. }
  33185. }
  33186. return newValue;
  33187. };
  33188. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33189. if (newValue !== currentValue) {
  33190. if (this._ondpaddown && newValue === 1) {
  33191. this._ondpaddown(buttonType);
  33192. }
  33193. if (this._ondpadup && newValue === 0) {
  33194. this._ondpadup(buttonType);
  33195. }
  33196. }
  33197. return newValue;
  33198. };
  33199. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33200. get: function () {
  33201. return this._buttonA;
  33202. },
  33203. set: function (value) {
  33204. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33205. },
  33206. enumerable: true,
  33207. configurable: true
  33208. });
  33209. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33210. get: function () {
  33211. return this._buttonB;
  33212. },
  33213. set: function (value) {
  33214. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33215. },
  33216. enumerable: true,
  33217. configurable: true
  33218. });
  33219. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33220. get: function () {
  33221. return this._buttonX;
  33222. },
  33223. set: function (value) {
  33224. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33225. },
  33226. enumerable: true,
  33227. configurable: true
  33228. });
  33229. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33230. get: function () {
  33231. return this._buttonY;
  33232. },
  33233. set: function (value) {
  33234. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33235. },
  33236. enumerable: true,
  33237. configurable: true
  33238. });
  33239. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33240. get: function () {
  33241. return this._buttonStart;
  33242. },
  33243. set: function (value) {
  33244. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33245. },
  33246. enumerable: true,
  33247. configurable: true
  33248. });
  33249. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33250. get: function () {
  33251. return this._buttonBack;
  33252. },
  33253. set: function (value) {
  33254. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33255. },
  33256. enumerable: true,
  33257. configurable: true
  33258. });
  33259. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33260. get: function () {
  33261. return this._buttonLB;
  33262. },
  33263. set: function (value) {
  33264. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33270. get: function () {
  33271. return this._buttonRB;
  33272. },
  33273. set: function (value) {
  33274. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33275. },
  33276. enumerable: true,
  33277. configurable: true
  33278. });
  33279. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33280. get: function () {
  33281. return this._buttonLeftStick;
  33282. },
  33283. set: function (value) {
  33284. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33285. },
  33286. enumerable: true,
  33287. configurable: true
  33288. });
  33289. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33290. get: function () {
  33291. return this._buttonRightStick;
  33292. },
  33293. set: function (value) {
  33294. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33295. },
  33296. enumerable: true,
  33297. configurable: true
  33298. });
  33299. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33300. get: function () {
  33301. return this._dPadUp;
  33302. },
  33303. set: function (value) {
  33304. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33305. },
  33306. enumerable: true,
  33307. configurable: true
  33308. });
  33309. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33310. get: function () {
  33311. return this._dPadDown;
  33312. },
  33313. set: function (value) {
  33314. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33315. },
  33316. enumerable: true,
  33317. configurable: true
  33318. });
  33319. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33320. get: function () {
  33321. return this._dPadLeft;
  33322. },
  33323. set: function (value) {
  33324. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33325. },
  33326. enumerable: true,
  33327. configurable: true
  33328. });
  33329. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33330. get: function () {
  33331. return this._dPadRight;
  33332. },
  33333. set: function (value) {
  33334. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33335. },
  33336. enumerable: true,
  33337. configurable: true
  33338. });
  33339. Xbox360Pad.prototype.update = function () {
  33340. _super.prototype.update.call(this);
  33341. this.buttonA = this.browserGamepad.buttons[0].value;
  33342. this.buttonB = this.browserGamepad.buttons[1].value;
  33343. this.buttonX = this.browserGamepad.buttons[2].value;
  33344. this.buttonY = this.browserGamepad.buttons[3].value;
  33345. this.buttonLB = this.browserGamepad.buttons[4].value;
  33346. this.buttonRB = this.browserGamepad.buttons[5].value;
  33347. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33348. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33349. this.buttonBack = this.browserGamepad.buttons[8].value;
  33350. this.buttonStart = this.browserGamepad.buttons[9].value;
  33351. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33352. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33353. this.dPadUp = this.browserGamepad.buttons[12].value;
  33354. this.dPadDown = this.browserGamepad.buttons[13].value;
  33355. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33356. this.dPadRight = this.browserGamepad.buttons[15].value;
  33357. };
  33358. return Xbox360Pad;
  33359. })(Gamepad);
  33360. BABYLON.Xbox360Pad = Xbox360Pad;
  33361. })(BABYLON || (BABYLON = {}));
  33362. var BABYLON;
  33363. (function (BABYLON) {
  33364. // We're mainly based on the logic defined into the FreeCamera code
  33365. var GamepadCamera = (function (_super) {
  33366. __extends(GamepadCamera, _super);
  33367. function GamepadCamera(name, position, scene) {
  33368. var _this = this;
  33369. _super.call(this, name, position, scene);
  33370. this.angularSensibility = 200;
  33371. this.moveSensibility = 75;
  33372. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33373. }
  33374. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33375. // Only the first gamepad can control the camera
  33376. if (gamepad.index === 0) {
  33377. this._gamepad = gamepad;
  33378. }
  33379. };
  33380. GamepadCamera.prototype._checkInputs = function () {
  33381. if (this._gamepad) {
  33382. var LSValues = this._gamepad.leftStick;
  33383. var normalizedLX = LSValues.x / this.moveSensibility;
  33384. var normalizedLY = LSValues.y / this.moveSensibility;
  33385. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33386. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33387. var RSValues = this._gamepad.rightStick;
  33388. var normalizedRX = RSValues.x / this.angularSensibility;
  33389. var normalizedRY = RSValues.y / this.angularSensibility;
  33390. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33391. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33392. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33393. var speed = this._computeLocalCameraSpeed() * 50.0;
  33394. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33395. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33396. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33397. }
  33398. _super.prototype._checkInputs.call(this);
  33399. };
  33400. GamepadCamera.prototype.dispose = function () {
  33401. this._gamepads.dispose();
  33402. _super.prototype.dispose.call(this);
  33403. };
  33404. return GamepadCamera;
  33405. })(BABYLON.FreeCamera);
  33406. BABYLON.GamepadCamera = GamepadCamera;
  33407. })(BABYLON || (BABYLON = {}));
  33408. var BABYLON;
  33409. (function (BABYLON) {
  33410. var Analyser = (function () {
  33411. function Analyser(scene) {
  33412. this.SMOOTHING = 0.75;
  33413. this.FFT_SIZE = 512;
  33414. this.BARGRAPHAMPLITUDE = 256;
  33415. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33416. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33417. this._scene = scene;
  33418. this._audioEngine = BABYLON.Engine.audioEngine;
  33419. if (this._audioEngine.canUseWebAudio) {
  33420. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33421. this._webAudioAnalyser.minDecibels = -140;
  33422. this._webAudioAnalyser.maxDecibels = 0;
  33423. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33424. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33425. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33426. }
  33427. }
  33428. Analyser.prototype.getFrequencyBinCount = function () {
  33429. if (this._audioEngine.canUseWebAudio) {
  33430. return this._webAudioAnalyser.frequencyBinCount;
  33431. }
  33432. else {
  33433. return 0;
  33434. }
  33435. };
  33436. Analyser.prototype.getByteFrequencyData = function () {
  33437. if (this._audioEngine.canUseWebAudio) {
  33438. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33439. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33440. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33441. }
  33442. return this._byteFreqs;
  33443. };
  33444. Analyser.prototype.getByteTimeDomainData = function () {
  33445. if (this._audioEngine.canUseWebAudio) {
  33446. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33447. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33448. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33449. }
  33450. return this._byteTime;
  33451. };
  33452. Analyser.prototype.getFloatFrequencyData = function () {
  33453. if (this._audioEngine.canUseWebAudio) {
  33454. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33455. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33456. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33457. }
  33458. return this._floatFreqs;
  33459. };
  33460. Analyser.prototype.drawDebugCanvas = function () {
  33461. var _this = this;
  33462. if (this._audioEngine.canUseWebAudio) {
  33463. if (!this._debugCanvas) {
  33464. this._debugCanvas = document.createElement("canvas");
  33465. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33466. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33467. this._debugCanvas.style.position = "absolute";
  33468. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33469. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33470. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33471. document.body.appendChild(this._debugCanvas);
  33472. this._registerFunc = function () {
  33473. _this.drawDebugCanvas();
  33474. };
  33475. this._scene.registerBeforeRender(this._registerFunc);
  33476. }
  33477. if (this._registerFunc) {
  33478. var workingArray = this.getByteFrequencyData();
  33479. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33480. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33481. // Draw the frequency domain chart.
  33482. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33483. var value = workingArray[i];
  33484. var percent = value / this.BARGRAPHAMPLITUDE;
  33485. var height = this.DEBUGCANVASSIZE.height * percent;
  33486. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33487. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33488. var hue = i / this.getFrequencyBinCount() * 360;
  33489. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33490. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33491. }
  33492. }
  33493. }
  33494. };
  33495. Analyser.prototype.stopDebugCanvas = function () {
  33496. if (this._debugCanvas) {
  33497. this._scene.unregisterBeforeRender(this._registerFunc);
  33498. this._registerFunc = null;
  33499. document.body.removeChild(this._debugCanvas);
  33500. this._debugCanvas = null;
  33501. this._debugCanvasContext = null;
  33502. }
  33503. };
  33504. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33505. if (this._audioEngine.canUseWebAudio) {
  33506. inputAudioNode.connect(this._webAudioAnalyser);
  33507. this._webAudioAnalyser.connect(outputAudioNode);
  33508. }
  33509. };
  33510. Analyser.prototype.dispose = function () {
  33511. if (this._audioEngine.canUseWebAudio) {
  33512. this._webAudioAnalyser.disconnect();
  33513. }
  33514. };
  33515. return Analyser;
  33516. })();
  33517. BABYLON.Analyser = Analyser;
  33518. })(BABYLON || (BABYLON = {}));
  33519. var BABYLON;
  33520. (function (BABYLON) {
  33521. var AudioEngine = (function () {
  33522. function AudioEngine() {
  33523. this._audioContext = null;
  33524. this._audioContextInitialized = false;
  33525. this.canUseWebAudio = false;
  33526. this.WarnedWebAudioUnsupported = false;
  33527. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33528. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33529. this.canUseWebAudio = true;
  33530. }
  33531. }
  33532. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33533. get: function () {
  33534. if (!this._audioContextInitialized) {
  33535. this._initializeAudioContext();
  33536. }
  33537. return this._audioContext;
  33538. },
  33539. enumerable: true,
  33540. configurable: true
  33541. });
  33542. AudioEngine.prototype._initializeAudioContext = function () {
  33543. try {
  33544. if (this.canUseWebAudio) {
  33545. this._audioContext = new AudioContext();
  33546. // create a global volume gain node
  33547. this.masterGain = this._audioContext.createGain();
  33548. this.masterGain.gain.value = 1;
  33549. this.masterGain.connect(this._audioContext.destination);
  33550. this._audioContextInitialized = true;
  33551. }
  33552. }
  33553. catch (e) {
  33554. this.canUseWebAudio = false;
  33555. BABYLON.Tools.Error("Web Audio: " + e.message);
  33556. }
  33557. };
  33558. AudioEngine.prototype.dispose = function () {
  33559. if (this.canUseWebAudio && this._audioContextInitialized) {
  33560. if (this._connectedAnalyser) {
  33561. this._connectedAnalyser.stopDebugCanvas();
  33562. this._connectedAnalyser.dispose();
  33563. this.masterGain.disconnect();
  33564. this.masterGain.connect(this._audioContext.destination);
  33565. this._connectedAnalyser = null;
  33566. }
  33567. this.masterGain.gain.value = 1;
  33568. }
  33569. this.WarnedWebAudioUnsupported = false;
  33570. };
  33571. AudioEngine.prototype.getGlobalVolume = function () {
  33572. if (this.canUseWebAudio && this._audioContextInitialized) {
  33573. return this.masterGain.gain.value;
  33574. }
  33575. else {
  33576. return -1;
  33577. }
  33578. };
  33579. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33580. if (this.canUseWebAudio && this._audioContextInitialized) {
  33581. this.masterGain.gain.value = newVolume;
  33582. }
  33583. };
  33584. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33585. if (this._connectedAnalyser) {
  33586. this._connectedAnalyser.stopDebugCanvas();
  33587. }
  33588. if (this.canUseWebAudio && this._audioContextInitialized) {
  33589. this._connectedAnalyser = analyser;
  33590. this.masterGain.disconnect();
  33591. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33592. }
  33593. };
  33594. return AudioEngine;
  33595. })();
  33596. BABYLON.AudioEngine = AudioEngine;
  33597. })(BABYLON || (BABYLON = {}));
  33598. var BABYLON;
  33599. (function (BABYLON) {
  33600. var Sound = (function () {
  33601. /**
  33602. * Create a sound and attach it to a scene
  33603. * @param name Name of your sound
  33604. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33605. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33606. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33607. */
  33608. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33609. var _this = this;
  33610. this.autoplay = false;
  33611. this.loop = false;
  33612. this.useCustomAttenuation = false;
  33613. this.spatialSound = false;
  33614. this.refDistance = 1;
  33615. this.rolloffFactor = 1;
  33616. this.maxDistance = 100;
  33617. this.distanceModel = "linear";
  33618. this._panningModel = "equalpower";
  33619. this._playbackRate = 1;
  33620. this._streaming = false;
  33621. this._startTime = 0;
  33622. this._startOffset = 0;
  33623. this._position = BABYLON.Vector3.Zero();
  33624. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33625. this._volume = 1;
  33626. this._isLoaded = false;
  33627. this._isReadyToPlay = false;
  33628. this.isPlaying = false;
  33629. this.isPaused = false;
  33630. this._isDirectional = false;
  33631. // Used if you'd like to create a directional sound.
  33632. // If not set, the sound will be omnidirectional
  33633. this._coneInnerAngle = 360;
  33634. this._coneOuterAngle = 360;
  33635. this._coneOuterGain = 0;
  33636. this._isOutputConnected = false;
  33637. this.name = name;
  33638. this._scene = scene;
  33639. this._readyToPlayCallback = readyToPlayCallback;
  33640. // Default custom attenuation function is a linear attenuation
  33641. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33642. if (currentDistance < maxDistance) {
  33643. return currentVolume * (1 - currentDistance / maxDistance);
  33644. }
  33645. else {
  33646. return 0;
  33647. }
  33648. };
  33649. if (options) {
  33650. this.autoplay = options.autoplay || false;
  33651. this.loop = options.loop || false;
  33652. // if volume === 0, we need another way to check this option
  33653. if (options.volume !== undefined) {
  33654. this._volume = options.volume;
  33655. }
  33656. this.spatialSound = options.spatialSound || false;
  33657. this.maxDistance = options.maxDistance || 100;
  33658. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33659. this.rolloffFactor = options.rolloffFactor || 1;
  33660. this.refDistance = options.refDistance || 1;
  33661. this.distanceModel = options.distanceModel || "linear";
  33662. this._playbackRate = options.playbackRate || 1;
  33663. this._streaming = options.streaming || false;
  33664. }
  33665. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33666. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33667. this._soundGain.gain.value = this._volume;
  33668. this._inputAudioNode = this._soundGain;
  33669. this._ouputAudioNode = this._soundGain;
  33670. if (this.spatialSound) {
  33671. this._createSpatialParameters();
  33672. }
  33673. this._scene.mainSoundTrack.AddSound(this);
  33674. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33675. if (urlOrArrayBuffer) {
  33676. // If it's an URL
  33677. if (typeof (urlOrArrayBuffer) === "string") {
  33678. // Loading sound using XHR2
  33679. if (!this._streaming) {
  33680. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33681. }
  33682. else {
  33683. this._htmlAudioElement = new Audio();
  33684. this._htmlAudioElement.src = urlOrArrayBuffer;
  33685. this._htmlAudioElement.controls = false;
  33686. this._htmlAudioElement.loop = this.loop;
  33687. this._htmlAudioElement.crossOrigin = "anonymous";
  33688. this._isReadyToPlay = true;
  33689. document.body.appendChild(this._htmlAudioElement);
  33690. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33691. if (this._readyToPlayCallback) {
  33692. window.setTimeout(function () {
  33693. _this._readyToPlayCallback();
  33694. }, 1000);
  33695. }
  33696. if (this.autoplay) {
  33697. this.play();
  33698. }
  33699. }
  33700. }
  33701. else {
  33702. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33703. this._soundLoaded(urlOrArrayBuffer);
  33704. }
  33705. else {
  33706. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33707. }
  33708. }
  33709. }
  33710. }
  33711. else {
  33712. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33713. this._scene.mainSoundTrack.AddSound(this);
  33714. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33715. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33716. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33717. }
  33718. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33719. if (this._readyToPlayCallback) {
  33720. window.setTimeout(function () {
  33721. _this._readyToPlayCallback();
  33722. }, 1000);
  33723. }
  33724. }
  33725. }
  33726. Sound.prototype.dispose = function () {
  33727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33728. if (this.isPlaying) {
  33729. this.stop();
  33730. }
  33731. this._isReadyToPlay = false;
  33732. if (this.soundTrackId === -1) {
  33733. this._scene.mainSoundTrack.RemoveSound(this);
  33734. }
  33735. else {
  33736. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33737. }
  33738. if (this._soundGain) {
  33739. this._soundGain.disconnect();
  33740. this._soundGain = null;
  33741. }
  33742. if (this._soundPanner) {
  33743. this._soundPanner.disconnect();
  33744. this._soundPanner = null;
  33745. }
  33746. if (this._soundSource) {
  33747. this._soundSource.disconnect();
  33748. this._soundSource = null;
  33749. }
  33750. this._audioBuffer = null;
  33751. if (this._htmlAudioElement) {
  33752. this._htmlAudioElement.pause();
  33753. this._htmlAudioElement.src = "";
  33754. document.body.removeChild(this._htmlAudioElement);
  33755. }
  33756. if (this._connectedMesh) {
  33757. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33758. this._connectedMesh = null;
  33759. }
  33760. }
  33761. };
  33762. Sound.prototype._soundLoaded = function (audioData) {
  33763. var _this = this;
  33764. this._isLoaded = true;
  33765. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33766. _this._audioBuffer = buffer;
  33767. _this._isReadyToPlay = true;
  33768. if (_this.autoplay) {
  33769. _this.play();
  33770. }
  33771. if (_this._readyToPlayCallback) {
  33772. _this._readyToPlayCallback();
  33773. }
  33774. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33775. };
  33776. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33777. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33778. this._audioBuffer = audioBuffer;
  33779. this._isReadyToPlay = true;
  33780. }
  33781. };
  33782. Sound.prototype.updateOptions = function (options) {
  33783. if (options) {
  33784. this.loop = options.loop || this.loop;
  33785. this.maxDistance = options.maxDistance || this.maxDistance;
  33786. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33787. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33788. this.refDistance = options.refDistance || this.refDistance;
  33789. this.distanceModel = options.distanceModel || this.distanceModel;
  33790. this._playbackRate = options.playbackRate || this._playbackRate;
  33791. this._updateSpatialParameters();
  33792. if (this.isPlaying) {
  33793. if (this._streaming) {
  33794. this._htmlAudioElement.playbackRate = this._playbackRate;
  33795. }
  33796. else {
  33797. this._soundSource.playbackRate.value = this._playbackRate;
  33798. }
  33799. }
  33800. }
  33801. };
  33802. Sound.prototype._createSpatialParameters = function () {
  33803. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33804. if (this._scene.headphone) {
  33805. this._panningModel = "HRTF";
  33806. }
  33807. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33808. this._updateSpatialParameters();
  33809. this._soundPanner.connect(this._ouputAudioNode);
  33810. this._inputAudioNode = this._soundPanner;
  33811. }
  33812. };
  33813. Sound.prototype._updateSpatialParameters = function () {
  33814. if (this.spatialSound) {
  33815. if (this.useCustomAttenuation) {
  33816. // Tricks to disable in a way embedded Web Audio attenuation
  33817. this._soundPanner.distanceModel = "linear";
  33818. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33819. this._soundPanner.refDistance = 1;
  33820. this._soundPanner.rolloffFactor = 1;
  33821. this._soundPanner.panningModel = this._panningModel;
  33822. }
  33823. else {
  33824. this._soundPanner.distanceModel = this.distanceModel;
  33825. this._soundPanner.maxDistance = this.maxDistance;
  33826. this._soundPanner.refDistance = this.refDistance;
  33827. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33828. this._soundPanner.panningModel = this._panningModel;
  33829. }
  33830. }
  33831. };
  33832. Sound.prototype.switchPanningModelToHRTF = function () {
  33833. this._panningModel = "HRTF";
  33834. this._switchPanningModel();
  33835. };
  33836. Sound.prototype.switchPanningModelToEqualPower = function () {
  33837. this._panningModel = "equalpower";
  33838. this._switchPanningModel();
  33839. };
  33840. Sound.prototype._switchPanningModel = function () {
  33841. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33842. this._soundPanner.panningModel = this._panningModel;
  33843. }
  33844. };
  33845. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33847. if (this._isOutputConnected) {
  33848. this._ouputAudioNode.disconnect();
  33849. }
  33850. this._ouputAudioNode.connect(soundTrackAudioNode);
  33851. this._isOutputConnected = true;
  33852. }
  33853. };
  33854. /**
  33855. * Transform this sound into a directional source
  33856. * @param coneInnerAngle Size of the inner cone in degree
  33857. * @param coneOuterAngle Size of the outer cone in degree
  33858. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33859. */
  33860. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33861. if (coneOuterAngle < coneInnerAngle) {
  33862. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33863. return;
  33864. }
  33865. this._coneInnerAngle = coneInnerAngle;
  33866. this._coneOuterAngle = coneOuterAngle;
  33867. this._coneOuterGain = coneOuterGain;
  33868. this._isDirectional = true;
  33869. if (this.isPlaying && this.loop) {
  33870. this.stop();
  33871. this.play();
  33872. }
  33873. };
  33874. Sound.prototype.setPosition = function (newPosition) {
  33875. this._position = newPosition;
  33876. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33877. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33878. }
  33879. };
  33880. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33881. this._localDirection = newLocalDirection;
  33882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33883. this._updateDirection();
  33884. }
  33885. };
  33886. Sound.prototype._updateDirection = function () {
  33887. var mat = this._connectedMesh.getWorldMatrix();
  33888. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33889. direction.normalize();
  33890. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33891. };
  33892. Sound.prototype.updateDistanceFromListener = function () {
  33893. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33894. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33895. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33896. }
  33897. };
  33898. Sound.prototype.setAttenuationFunction = function (callback) {
  33899. this._customAttenuationFunction = callback;
  33900. };
  33901. /**
  33902. * Play the sound
  33903. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33904. */
  33905. Sound.prototype.play = function (time) {
  33906. var _this = this;
  33907. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33908. try {
  33909. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33910. if (!this._soundSource || !this._streamingSource) {
  33911. if (this.spatialSound) {
  33912. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33913. if (this._isDirectional) {
  33914. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33915. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33916. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33917. if (this._connectedMesh) {
  33918. this._updateDirection();
  33919. }
  33920. else {
  33921. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33922. }
  33923. }
  33924. }
  33925. }
  33926. if (this._streaming) {
  33927. if (!this._streamingSource) {
  33928. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33929. this._htmlAudioElement.onended = function () { _this._onended(); };
  33930. this._htmlAudioElement.playbackRate = this._playbackRate;
  33931. }
  33932. this._streamingSource.disconnect();
  33933. this._streamingSource.connect(this._inputAudioNode);
  33934. this._htmlAudioElement.play();
  33935. }
  33936. else {
  33937. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33938. this._soundSource.buffer = this._audioBuffer;
  33939. this._soundSource.connect(this._inputAudioNode);
  33940. this._soundSource.loop = this.loop;
  33941. this._soundSource.playbackRate.value = this._playbackRate;
  33942. this._soundSource.onended = function () { _this._onended(); };
  33943. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33944. }
  33945. this._startTime = startTime;
  33946. this.isPlaying = true;
  33947. this.isPaused = false;
  33948. }
  33949. catch (ex) {
  33950. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33951. }
  33952. }
  33953. };
  33954. Sound.prototype._onended = function () {
  33955. this.isPlaying = false;
  33956. if (this.onended) {
  33957. this.onended();
  33958. }
  33959. };
  33960. /**
  33961. * Stop the sound
  33962. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33963. */
  33964. Sound.prototype.stop = function (time) {
  33965. if (this.isPlaying) {
  33966. if (this._streaming) {
  33967. this._htmlAudioElement.pause();
  33968. // Test needed for Firefox or it will generate an Invalid State Error
  33969. if (this._htmlAudioElement.currentTime > 0) {
  33970. this._htmlAudioElement.currentTime = 0;
  33971. }
  33972. }
  33973. else {
  33974. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33975. this._soundSource.stop(stopTime);
  33976. }
  33977. this.isPlaying = false;
  33978. }
  33979. };
  33980. Sound.prototype.pause = function () {
  33981. if (this.isPlaying) {
  33982. if (this._streaming) {
  33983. this._htmlAudioElement.pause();
  33984. }
  33985. else {
  33986. this.stop(0);
  33987. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33988. }
  33989. this.isPaused = true;
  33990. }
  33991. };
  33992. Sound.prototype.setVolume = function (newVolume, time) {
  33993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33994. if (time) {
  33995. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33996. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33997. }
  33998. else {
  33999. this._soundGain.gain.value = newVolume;
  34000. }
  34001. }
  34002. this._volume = newVolume;
  34003. };
  34004. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34005. this._playbackRate = newPlaybackRate;
  34006. if (this.isPlaying) {
  34007. if (this._streaming) {
  34008. this._htmlAudioElement.playbackRate = this._playbackRate;
  34009. }
  34010. else {
  34011. this._soundSource.playbackRate.value = this._playbackRate;
  34012. }
  34013. }
  34014. };
  34015. Sound.prototype.getVolume = function () {
  34016. return this._volume;
  34017. };
  34018. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34019. var _this = this;
  34020. this._connectedMesh = meshToConnectTo;
  34021. if (!this.spatialSound) {
  34022. this.spatialSound = true;
  34023. this._createSpatialParameters();
  34024. if (this.isPlaying && this.loop) {
  34025. this.stop();
  34026. this.play();
  34027. }
  34028. }
  34029. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34030. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34031. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34032. };
  34033. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34034. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34035. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34036. this._updateDirection();
  34037. }
  34038. };
  34039. return Sound;
  34040. })();
  34041. BABYLON.Sound = Sound;
  34042. })(BABYLON || (BABYLON = {}));
  34043. var BABYLON;
  34044. (function (BABYLON) {
  34045. var SoundTrack = (function () {
  34046. function SoundTrack(scene, options) {
  34047. this.id = -1;
  34048. this._isMainTrack = false;
  34049. this._isInitialized = false;
  34050. this._scene = scene;
  34051. this.soundCollection = new Array();
  34052. this._options = options;
  34053. if (!this._isMainTrack) {
  34054. this._scene.soundTracks.push(this);
  34055. this.id = this._scene.soundTracks.length - 1;
  34056. }
  34057. }
  34058. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34059. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34060. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34061. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34062. if (this._options) {
  34063. if (this._options.volume) {
  34064. this._outputAudioNode.gain.value = this._options.volume;
  34065. }
  34066. if (this._options.mainTrack) {
  34067. this._isMainTrack = this._options.mainTrack;
  34068. }
  34069. }
  34070. this._isInitialized = true;
  34071. }
  34072. };
  34073. SoundTrack.prototype.dispose = function () {
  34074. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34075. if (this._connectedAnalyser) {
  34076. this._connectedAnalyser.stopDebugCanvas();
  34077. }
  34078. while (this.soundCollection.length) {
  34079. this.soundCollection[0].dispose();
  34080. }
  34081. if (this._outputAudioNode) {
  34082. this._outputAudioNode.disconnect();
  34083. }
  34084. this._outputAudioNode = null;
  34085. }
  34086. };
  34087. SoundTrack.prototype.AddSound = function (sound) {
  34088. if (!this._isInitialized) {
  34089. this._initializeSoundTrackAudioGraph();
  34090. }
  34091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34092. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34093. }
  34094. if (sound.soundTrackId) {
  34095. if (sound.soundTrackId === -1) {
  34096. this._scene.mainSoundTrack.RemoveSound(sound);
  34097. }
  34098. else {
  34099. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34100. }
  34101. }
  34102. this.soundCollection.push(sound);
  34103. sound.soundTrackId = this.id;
  34104. };
  34105. SoundTrack.prototype.RemoveSound = function (sound) {
  34106. var index = this.soundCollection.indexOf(sound);
  34107. if (index !== -1) {
  34108. this.soundCollection.splice(index, 1);
  34109. }
  34110. };
  34111. SoundTrack.prototype.setVolume = function (newVolume) {
  34112. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34113. this._outputAudioNode.gain.value = newVolume;
  34114. }
  34115. };
  34116. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34117. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34118. for (var i = 0; i < this.soundCollection.length; i++) {
  34119. this.soundCollection[i].switchPanningModelToHRTF();
  34120. }
  34121. }
  34122. };
  34123. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34124. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34125. for (var i = 0; i < this.soundCollection.length; i++) {
  34126. this.soundCollection[i].switchPanningModelToEqualPower();
  34127. }
  34128. }
  34129. };
  34130. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34131. if (this._connectedAnalyser) {
  34132. this._connectedAnalyser.stopDebugCanvas();
  34133. }
  34134. this._connectedAnalyser = analyser;
  34135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34136. this._outputAudioNode.disconnect();
  34137. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34138. }
  34139. };
  34140. return SoundTrack;
  34141. })();
  34142. BABYLON.SoundTrack = SoundTrack;
  34143. })(BABYLON || (BABYLON = {}));
  34144. var BABYLON;
  34145. (function (BABYLON) {
  34146. var DepthRenderer = (function () {
  34147. function DepthRenderer(scene, type) {
  34148. var _this = this;
  34149. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34150. this._viewMatrix = BABYLON.Matrix.Zero();
  34151. this._projectionMatrix = BABYLON.Matrix.Zero();
  34152. this._transformMatrix = BABYLON.Matrix.Zero();
  34153. this._worldViewProjection = BABYLON.Matrix.Zero();
  34154. this._scene = scene;
  34155. var engine = scene.getEngine();
  34156. // Render target
  34157. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34158. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34159. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34160. this._depthMap.refreshRate = 1;
  34161. this._depthMap.renderParticles = false;
  34162. this._depthMap.renderList = null;
  34163. // set default depth value to 1.0 (far away)
  34164. this._depthMap.onClear = function (engine) {
  34165. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34166. };
  34167. // Custom render function
  34168. var renderSubMesh = function (subMesh) {
  34169. var mesh = subMesh.getRenderingMesh();
  34170. var scene = _this._scene;
  34171. var engine = scene.getEngine();
  34172. // Culling
  34173. engine.setState(subMesh.getMaterial().backFaceCulling);
  34174. // Managing instances
  34175. var batch = mesh._getInstancesRenderList(subMesh._id);
  34176. if (batch.mustReturn) {
  34177. return;
  34178. }
  34179. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34180. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34181. engine.enableEffect(_this._effect);
  34182. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34183. var material = subMesh.getMaterial();
  34184. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34185. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34186. // Alpha test
  34187. if (material && material.needAlphaTesting()) {
  34188. var alphaTexture = material.getAlphaTestTexture();
  34189. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34190. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34191. }
  34192. // Bones
  34193. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34194. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34195. }
  34196. // Draw
  34197. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34198. }
  34199. };
  34200. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34201. var index;
  34202. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34203. renderSubMesh(opaqueSubMeshes.data[index]);
  34204. }
  34205. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34206. renderSubMesh(alphaTestSubMeshes.data[index]);
  34207. }
  34208. };
  34209. }
  34210. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34211. var defines = [];
  34212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34213. var mesh = subMesh.getMesh();
  34214. var scene = mesh.getScene();
  34215. var material = subMesh.getMaterial();
  34216. // Alpha test
  34217. if (material && material.needAlphaTesting()) {
  34218. defines.push("#define ALPHATEST");
  34219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34220. attribs.push(BABYLON.VertexBuffer.UVKind);
  34221. defines.push("#define UV1");
  34222. }
  34223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34225. defines.push("#define UV2");
  34226. }
  34227. }
  34228. // Bones
  34229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34232. if (mesh.numBoneInfluencers > 4) {
  34233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34235. }
  34236. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34237. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34238. }
  34239. else {
  34240. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34241. }
  34242. // Instances
  34243. if (useInstances) {
  34244. defines.push("#define INSTANCES");
  34245. attribs.push("world0");
  34246. attribs.push("world1");
  34247. attribs.push("world2");
  34248. attribs.push("world3");
  34249. }
  34250. // Get correct effect
  34251. var join = defines.join("\n");
  34252. if (this._cachedDefines !== join) {
  34253. this._cachedDefines = join;
  34254. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34255. }
  34256. return this._effect.isReady();
  34257. };
  34258. DepthRenderer.prototype.getDepthMap = function () {
  34259. return this._depthMap;
  34260. };
  34261. // Methods
  34262. DepthRenderer.prototype.dispose = function () {
  34263. this._depthMap.dispose();
  34264. };
  34265. return DepthRenderer;
  34266. })();
  34267. BABYLON.DepthRenderer = DepthRenderer;
  34268. })(BABYLON || (BABYLON = {}));
  34269. var BABYLON;
  34270. (function (BABYLON) {
  34271. var SSAORenderingPipeline = (function (_super) {
  34272. __extends(SSAORenderingPipeline, _super);
  34273. /**
  34274. * @constructor
  34275. * @param {string} name - The rendering pipeline name
  34276. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34277. * @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 }
  34278. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34279. */
  34280. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34281. var _this = this;
  34282. _super.call(this, scene.getEngine(), name);
  34283. // Members
  34284. /**
  34285. * The PassPostProcess id in the pipeline that contains the original scene color
  34286. * @type {string}
  34287. */
  34288. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34289. /**
  34290. * The SSAO PostProcess id in the pipeline
  34291. * @type {string}
  34292. */
  34293. this.SSAORenderEffect = "SSAORenderEffect";
  34294. /**
  34295. * The horizontal blur PostProcess id in the pipeline
  34296. * @type {string}
  34297. */
  34298. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34299. /**
  34300. * The vertical blur PostProcess id in the pipeline
  34301. * @type {string}
  34302. */
  34303. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34304. /**
  34305. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34306. * @type {string}
  34307. */
  34308. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34309. /**
  34310. * The output strength of the SSAO post-process. Default value is 1.0.
  34311. * @type {number}
  34312. */
  34313. this.totalStrength = 1.0;
  34314. /**
  34315. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34316. * @type {number}
  34317. */
  34318. this.radius = 0.0001;
  34319. /**
  34320. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34321. * Must not be equal to fallOff and superior to fallOff.
  34322. * Default value is 0.975
  34323. * @type {number}
  34324. */
  34325. this.area = 0.0075;
  34326. /**
  34327. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34328. * Must not be equal to area and inferior to area.
  34329. * Default value is 0.0
  34330. * @type {number}
  34331. */
  34332. this.fallOff = 0.000001;
  34333. /**
  34334. * The base color of the SSAO post-process
  34335. * The final result is "base + ssao" between [0, 1]
  34336. * @type {number}
  34337. */
  34338. this.base = 0.5;
  34339. this._firstUpdate = true;
  34340. this._scene = scene;
  34341. // Set up assets
  34342. this._createRandomTexture();
  34343. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34344. var ssaoRatio = ratio.ssaoRatio || ratio;
  34345. var combineRatio = ratio.combineRatio || ratio;
  34346. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34347. this._createSSAOPostProcess(ssaoRatio);
  34348. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34349. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34350. this._createSSAOCombinePostProcess(combineRatio);
  34351. // Set up pipeline
  34352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34353. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34354. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34355. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34357. // Finish
  34358. scene.postProcessRenderPipelineManager.addPipeline(this);
  34359. if (cameras)
  34360. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34361. }
  34362. // Public Methods
  34363. /**
  34364. * Returns the horizontal blur PostProcess
  34365. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34366. */
  34367. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34368. return this._blurHPostProcess;
  34369. };
  34370. /**
  34371. * Returns the vertical blur PostProcess
  34372. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34373. */
  34374. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34375. return this._blurVPostProcess;
  34376. };
  34377. /**
  34378. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34379. */
  34380. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34381. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34382. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34383. this._originalColorPostProcess = undefined;
  34384. this._ssaoPostProcess = undefined;
  34385. this._blurHPostProcess = undefined;
  34386. this._blurVPostProcess = undefined;
  34387. this._ssaoCombinePostProcess = undefined;
  34388. this._randomTexture.dispose();
  34389. if (disableDepthRender)
  34390. this._scene.disableDepthRenderer();
  34391. };
  34392. // Private Methods
  34393. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34394. var _this = this;
  34395. var numSamples = 16;
  34396. var sampleSphere = [
  34397. 0.5381, 0.1856, -0.4319,
  34398. 0.1379, 0.2486, 0.4430,
  34399. 0.3371, 0.5679, -0.0057,
  34400. -0.6999, -0.0451, -0.0019,
  34401. 0.0689, -0.1598, -0.8547,
  34402. 0.0560, 0.0069, -0.1843,
  34403. -0.0146, 0.1402, 0.0762,
  34404. 0.0100, -0.1924, -0.0344,
  34405. -0.3577, -0.5301, -0.4358,
  34406. -0.3169, 0.1063, 0.0158,
  34407. 0.0103, -0.5869, 0.0046,
  34408. -0.0897, -0.4940, 0.3287,
  34409. 0.7119, -0.0154, -0.0918,
  34410. -0.0533, 0.0596, -0.5411,
  34411. 0.0352, -0.0631, 0.5460,
  34412. -0.4776, 0.2847, -0.0271
  34413. ];
  34414. var samplesFactor = 1.0 / numSamples;
  34415. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34416. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34417. "area", "fallOff", "base"
  34418. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34419. this._ssaoPostProcess.onApply = function (effect) {
  34420. if (_this._firstUpdate) {
  34421. effect.setArray3("sampleSphere", sampleSphere);
  34422. effect.setFloat("samplesFactor", samplesFactor);
  34423. effect.setFloat("randTextureTiles", 4.0);
  34424. _this._firstUpdate = false;
  34425. }
  34426. effect.setFloat("totalStrength", _this.totalStrength);
  34427. effect.setFloat("radius", _this.radius);
  34428. effect.setFloat("area", _this.area);
  34429. effect.setFloat("fallOff", _this.fallOff);
  34430. effect.setFloat("base", _this.base);
  34431. effect.setTexture("textureSampler", _this._depthTexture);
  34432. effect.setTexture("randomSampler", _this._randomTexture);
  34433. };
  34434. };
  34435. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34436. var _this = this;
  34437. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34438. this._ssaoCombinePostProcess.onApply = function (effect) {
  34439. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34440. };
  34441. };
  34442. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34443. var size = 512;
  34444. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34445. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34446. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34447. var context = this._randomTexture.getContext();
  34448. var rand = function (min, max) {
  34449. return Math.random() * (max - min) + min;
  34450. };
  34451. var randVector = BABYLON.Vector3.Zero();
  34452. for (var x = 0; x < size; x++) {
  34453. for (var y = 0; y < size; y++) {
  34454. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34455. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34456. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34457. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34458. context.fillRect(x, y, 1, 1);
  34459. }
  34460. }
  34461. this._randomTexture.update(false);
  34462. };
  34463. return SSAORenderingPipeline;
  34464. })(BABYLON.PostProcessRenderPipeline);
  34465. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34466. })(BABYLON || (BABYLON = {}));
  34467. var BABYLON;
  34468. (function (BABYLON) {
  34469. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34470. var VolumetricLightScatteringPostProcess = (function (_super) {
  34471. __extends(VolumetricLightScatteringPostProcess, _super);
  34472. /**
  34473. * @constructor
  34474. * @param {string} name - The post-process name
  34475. * @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)
  34476. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34477. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34478. * @param {number} samples - The post-process quality, default 100
  34479. * @param {number} samplingMode - The post-process filtering mode
  34480. * @param {BABYLON.Engine} engine - The babylon engine
  34481. * @param {boolean} reusable - If the post-process is reusable
  34482. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34483. */
  34484. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34485. var _this = this;
  34486. if (samples === void 0) { samples = 100; }
  34487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34488. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34489. this._screenCoordinates = BABYLON.Vector2.Zero();
  34490. /**
  34491. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34492. * @type {boolean}
  34493. */
  34494. this.useCustomMeshPosition = false;
  34495. /**
  34496. * If the post-process should inverse the light scattering direction
  34497. * @type {boolean}
  34498. */
  34499. this.invert = true;
  34500. /**
  34501. * Set to true to use the diffuseColor instead of the diffuseTexture
  34502. * @type {boolean}
  34503. */
  34504. this.useDiffuseColor = false;
  34505. /**
  34506. * Array containing the excluded meshes not rendered in the internal pass
  34507. */
  34508. this.excludedMeshes = new Array();
  34509. /**
  34510. * Controls the overall intensity of the post-process
  34511. * @type {number}
  34512. */
  34513. this.exposure = 0.3;
  34514. /**
  34515. * Dissipates each sample's contribution in range [0, 1]
  34516. * @type {number}
  34517. */
  34518. this.decay = 0.96815;
  34519. /**
  34520. * Controls the overall intensity of each sample
  34521. * @type {number}
  34522. */
  34523. this.weight = 0.58767;
  34524. /**
  34525. * Controls the density of each sample
  34526. * @type {number}
  34527. */
  34528. this.density = 0.926;
  34529. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34530. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34531. // Configure mesh
  34532. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34533. // Configure
  34534. this._createPass(scene, ratio.passRatio || ratio);
  34535. this.onActivate = function (camera) {
  34536. if (!_this.isSupported) {
  34537. _this.dispose(camera);
  34538. }
  34539. _this.onActivate = null;
  34540. };
  34541. this.onApply = function (effect) {
  34542. _this._updateMeshScreenCoordinates(scene);
  34543. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34544. effect.setFloat("exposure", _this.exposure);
  34545. effect.setFloat("decay", _this.decay);
  34546. effect.setFloat("weight", _this.weight);
  34547. effect.setFloat("density", _this.density);
  34548. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34549. };
  34550. }
  34551. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34552. var mesh = subMesh.getMesh();
  34553. var defines = [];
  34554. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34555. var material = subMesh.getMaterial();
  34556. var needUV = false;
  34557. // Render this.mesh as default
  34558. if (mesh === this.mesh) {
  34559. if (this.useDiffuseColor) {
  34560. defines.push("#define DIFFUSE_COLOR_RENDER");
  34561. }
  34562. else if (material) {
  34563. if (material.diffuseTexture !== undefined) {
  34564. defines.push("#define BASIC_RENDER");
  34565. }
  34566. else {
  34567. defines.push("#define DIFFUSE_COLOR_RENDER");
  34568. }
  34569. }
  34570. defines.push("#define NEED_UV");
  34571. needUV = true;
  34572. }
  34573. // Alpha test
  34574. if (material) {
  34575. if (material.needAlphaTesting()) {
  34576. defines.push("#define ALPHATEST");
  34577. }
  34578. if (material.opacityTexture !== undefined) {
  34579. defines.push("#define OPACITY");
  34580. if (material.opacityTexture.getAlphaFromRGB) {
  34581. defines.push("#define OPACITYRGB");
  34582. }
  34583. if (!needUV) {
  34584. defines.push("#define NEED_UV");
  34585. }
  34586. }
  34587. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34588. attribs.push(BABYLON.VertexBuffer.UVKind);
  34589. defines.push("#define UV1");
  34590. }
  34591. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34592. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34593. defines.push("#define UV2");
  34594. }
  34595. }
  34596. // Bones
  34597. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34598. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34599. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34600. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34601. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34602. }
  34603. else {
  34604. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34605. }
  34606. // Instances
  34607. if (useInstances) {
  34608. defines.push("#define INSTANCES");
  34609. attribs.push("world0");
  34610. attribs.push("world1");
  34611. attribs.push("world2");
  34612. attribs.push("world3");
  34613. }
  34614. // Get correct effect
  34615. var join = defines.join("\n");
  34616. if (this._cachedDefines !== join) {
  34617. this._cachedDefines = join;
  34618. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34619. }
  34620. return this._volumetricLightScatteringPass.isReady();
  34621. };
  34622. /**
  34623. * Sets the new light position for light scattering effect
  34624. * @param {BABYLON.Vector3} The new custom light position
  34625. */
  34626. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34627. this._customMeshPosition = position;
  34628. };
  34629. /**
  34630. * Returns the light position for light scattering effect
  34631. * @return {BABYLON.Vector3} The custom light position
  34632. */
  34633. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34634. return this._customMeshPosition;
  34635. };
  34636. /**
  34637. * Disposes the internal assets and detaches the post-process from the camera
  34638. */
  34639. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34640. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34641. if (rttIndex !== -1) {
  34642. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34643. }
  34644. this._volumetricLightScatteringRTT.dispose();
  34645. _super.prototype.dispose.call(this, camera);
  34646. };
  34647. /**
  34648. * Returns the render target texture used by the post-process
  34649. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34650. */
  34651. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34652. return this._volumetricLightScatteringRTT;
  34653. };
  34654. // Private methods
  34655. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34656. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34657. return true;
  34658. }
  34659. return false;
  34660. };
  34661. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34662. var _this = this;
  34663. var engine = scene.getEngine();
  34664. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34665. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34666. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34667. this._volumetricLightScatteringRTT.renderList = null;
  34668. this._volumetricLightScatteringRTT.renderParticles = false;
  34669. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34670. // Custom render function for submeshes
  34671. var renderSubMesh = function (subMesh) {
  34672. var mesh = subMesh.getRenderingMesh();
  34673. if (_this._meshExcluded(mesh)) {
  34674. return;
  34675. }
  34676. var scene = mesh.getScene();
  34677. var engine = scene.getEngine();
  34678. // Culling
  34679. engine.setState(subMesh.getMaterial().backFaceCulling);
  34680. // Managing instances
  34681. var batch = mesh._getInstancesRenderList(subMesh._id);
  34682. if (batch.mustReturn) {
  34683. return;
  34684. }
  34685. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34686. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34687. engine.enableEffect(_this._volumetricLightScatteringPass);
  34688. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34689. var material = subMesh.getMaterial();
  34690. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34691. // Alpha test
  34692. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34693. var alphaTexture = material.getAlphaTestTexture();
  34694. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34695. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34696. }
  34697. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34698. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34699. if (alphaTexture) {
  34700. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34701. }
  34702. }
  34703. if (material.opacityTexture !== undefined) {
  34704. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34705. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34706. }
  34707. }
  34708. // Bones
  34709. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34710. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34711. }
  34712. // Draw
  34713. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34714. }
  34715. };
  34716. // Render target texture callbacks
  34717. var savedSceneClearColor;
  34718. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34719. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34720. savedSceneClearColor = scene.clearColor;
  34721. scene.clearColor = sceneClearColor;
  34722. };
  34723. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34724. scene.clearColor = savedSceneClearColor;
  34725. };
  34726. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34727. var engine = scene.getEngine();
  34728. var index;
  34729. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34730. renderSubMesh(opaqueSubMeshes.data[index]);
  34731. }
  34732. engine.setAlphaTesting(true);
  34733. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34734. renderSubMesh(alphaTestSubMeshes.data[index]);
  34735. }
  34736. engine.setAlphaTesting(false);
  34737. if (transparentSubMeshes.length) {
  34738. // Sort sub meshes
  34739. for (index = 0; index < transparentSubMeshes.length; index++) {
  34740. var submesh = transparentSubMeshes.data[index];
  34741. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34742. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34743. }
  34744. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34745. sortedArray.sort(function (a, b) {
  34746. // Alpha index first
  34747. if (a._alphaIndex > b._alphaIndex) {
  34748. return 1;
  34749. }
  34750. if (a._alphaIndex < b._alphaIndex) {
  34751. return -1;
  34752. }
  34753. // Then distance to camera
  34754. if (a._distanceToCamera < b._distanceToCamera) {
  34755. return 1;
  34756. }
  34757. if (a._distanceToCamera > b._distanceToCamera) {
  34758. return -1;
  34759. }
  34760. return 0;
  34761. });
  34762. // Render sub meshes
  34763. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34764. for (index = 0; index < sortedArray.length; index++) {
  34765. renderSubMesh(sortedArray[index]);
  34766. }
  34767. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34768. }
  34769. };
  34770. };
  34771. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34772. var transform = scene.getTransformMatrix();
  34773. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34774. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34775. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34776. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34777. if (this.invert)
  34778. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34779. };
  34780. // Static methods
  34781. /**
  34782. * Creates a default mesh for the Volumeric Light Scattering post-process
  34783. * @param {string} The mesh name
  34784. * @param {BABYLON.Scene} The scene where to create the mesh
  34785. * @return {BABYLON.Mesh} the default mesh
  34786. */
  34787. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34788. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34789. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34790. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34791. return mesh;
  34792. };
  34793. return VolumetricLightScatteringPostProcess;
  34794. })(BABYLON.PostProcess);
  34795. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34796. })(BABYLON || (BABYLON = {}));
  34797. var BABYLON;
  34798. (function (BABYLON) {
  34799. var LensRenderingPipeline = (function (_super) {
  34800. __extends(LensRenderingPipeline, _super);
  34801. /**
  34802. * @constructor
  34803. *
  34804. * Effect parameters are as follow:
  34805. * {
  34806. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34807. * edge_blur: number; // from 0 to x (1 for realism)
  34808. * distortion: number; // from 0 to x (1 for realism)
  34809. * grain_amount: number; // from 0 to 1
  34810. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34811. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34812. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34813. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34814. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34815. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34816. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34817. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34818. * }
  34819. * Note: if an effect parameter is unset, effect is disabled
  34820. *
  34821. * @param {string} name - The rendering pipeline name
  34822. * @param {object} parameters - An object containing all parameters (see above)
  34823. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34824. * @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)
  34825. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34826. */
  34827. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34828. var _this = this;
  34829. if (ratio === void 0) { ratio = 1.0; }
  34830. _super.call(this, scene.getEngine(), name);
  34831. // Lens effects can be of the following:
  34832. // - chromatic aberration (slight shift of RGB colors)
  34833. // - blur on the edge of the lens
  34834. // - lens distortion
  34835. // - depth-of-field blur & highlights enhancing
  34836. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34837. // - grain effect (noise or custom texture)
  34838. // Two additional texture samplers are needed:
  34839. // - depth map (for depth-of-field)
  34840. // - grain texture
  34841. /**
  34842. * The chromatic aberration PostProcess id in the pipeline
  34843. * @type {string}
  34844. */
  34845. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34846. /**
  34847. * The highlights enhancing PostProcess id in the pipeline
  34848. * @type {string}
  34849. */
  34850. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34851. /**
  34852. * The depth-of-field PostProcess id in the pipeline
  34853. * @type {string}
  34854. */
  34855. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34856. this._scene = scene;
  34857. // Fetch texture samplers
  34858. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34859. if (parameters.grain_texture) {
  34860. this._grainTexture = parameters.grain_texture;
  34861. }
  34862. else {
  34863. this._createGrainTexture();
  34864. }
  34865. // save parameters
  34866. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34867. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34868. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34869. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34870. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34871. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34872. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34873. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34874. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34875. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34876. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34877. // Create effects
  34878. this._createChromaticAberrationPostProcess(ratio);
  34879. this._createHighlightsPostProcess(ratio);
  34880. this._createDepthOfFieldPostProcess(ratio / 4);
  34881. // Set up pipeline
  34882. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34883. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34885. if (this._highlightsGain === -1) {
  34886. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34887. }
  34888. // Finish
  34889. scene.postProcessRenderPipelineManager.addPipeline(this);
  34890. if (cameras) {
  34891. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34892. }
  34893. }
  34894. // public methods (self explanatory)
  34895. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34896. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34897. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34898. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34899. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34900. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34901. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34902. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34903. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34904. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34905. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34906. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34907. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34908. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34909. };
  34910. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34911. this._highlightsPostProcess.updateEffect();
  34912. };
  34913. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34914. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34915. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34916. this._highlightsGain = amount;
  34917. };
  34918. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34919. if (this._highlightsGain === -1) {
  34920. this._highlightsGain = 1.0;
  34921. }
  34922. this._highlightsThreshold = amount;
  34923. };
  34924. LensRenderingPipeline.prototype.disableHighlights = function () {
  34925. this._highlightsGain = -1;
  34926. };
  34927. /**
  34928. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34929. */
  34930. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34931. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34932. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34933. this._chromaticAberrationPostProcess = undefined;
  34934. this._highlightsPostProcess = undefined;
  34935. this._depthOfFieldPostProcess = undefined;
  34936. this._grainTexture.dispose();
  34937. if (disableDepthRender)
  34938. this._scene.disableDepthRenderer();
  34939. };
  34940. // colors shifting and distortion
  34941. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34942. var _this = this;
  34943. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34944. [], // samplers
  34945. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34946. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34947. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34948. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34949. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34950. };
  34951. };
  34952. // highlights enhancing
  34953. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34954. var _this = this;
  34955. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34956. [], // samplers
  34957. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34958. this._highlightsPostProcess.onApply = function (effect) {
  34959. effect.setFloat('gain', _this._highlightsGain);
  34960. effect.setFloat('threshold', _this._highlightsThreshold);
  34961. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34962. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34963. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34964. };
  34965. };
  34966. // colors shifting and distortion
  34967. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34968. var _this = this;
  34969. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34970. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34971. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34972. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34973. this._depthOfFieldPostProcess.onApply = function (effect) {
  34974. effect.setTexture("depthSampler", _this._depthTexture);
  34975. effect.setTexture("grainSampler", _this._grainTexture);
  34976. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34977. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34978. effect.setFloat('grain_amount', _this._grainAmount);
  34979. effect.setBool('blur_noise', _this._blurNoise);
  34980. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34981. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34982. effect.setFloat('distortion', _this._distortion);
  34983. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34984. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34985. effect.setFloat('aperture', _this._dofAperture);
  34986. effect.setFloat('darken', _this._dofDarken);
  34987. effect.setFloat('edge_blur', _this._edgeBlur);
  34988. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34989. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34990. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34991. };
  34992. };
  34993. // creates a black and white random noise texture, 512x512
  34994. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34995. var size = 512;
  34996. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34997. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34998. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34999. var context = this._grainTexture.getContext();
  35000. var rand = function (min, max) {
  35001. return Math.random() * (max - min) + min;
  35002. };
  35003. var value;
  35004. for (var x = 0; x < size; x++) {
  35005. for (var y = 0; y < size; y++) {
  35006. value = Math.floor(rand(0.42, 0.58) * 255);
  35007. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35008. context.fillRect(x, y, 1, 1);
  35009. }
  35010. }
  35011. this._grainTexture.update(false);
  35012. };
  35013. return LensRenderingPipeline;
  35014. })(BABYLON.PostProcessRenderPipeline);
  35015. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35016. })(BABYLON || (BABYLON = {}));
  35017. //
  35018. // This post-process allows the modification of rendered colors by using
  35019. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35020. //
  35021. // The object needs to be provided an url to a texture containing the color
  35022. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35023. // Use an image editing software to tweak the LUT to match your needs.
  35024. //
  35025. // For an example of a color LUT, see here:
  35026. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35027. // For explanations on color grading, see here:
  35028. // http://udn.epicgames.com/Three/ColorGrading.html
  35029. //
  35030. var BABYLON;
  35031. (function (BABYLON) {
  35032. var ColorCorrectionPostProcess = (function (_super) {
  35033. __extends(ColorCorrectionPostProcess, _super);
  35034. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35035. var _this = this;
  35036. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35037. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35038. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35039. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35040. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35041. this.onApply = function (effect) {
  35042. effect.setTexture("colorTable", _this._colorTableTexture);
  35043. };
  35044. }
  35045. return ColorCorrectionPostProcess;
  35046. })(BABYLON.PostProcess);
  35047. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35048. })(BABYLON || (BABYLON = {}));
  35049. var BABYLON;
  35050. (function (BABYLON) {
  35051. var AnaglyphFreeCamera = (function (_super) {
  35052. __extends(AnaglyphFreeCamera, _super);
  35053. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35054. _super.call(this, name, position, scene);
  35055. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35056. }
  35057. return AnaglyphFreeCamera;
  35058. })(BABYLON.FreeCamera);
  35059. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35060. var AnaglyphArcRotateCamera = (function (_super) {
  35061. __extends(AnaglyphArcRotateCamera, _super);
  35062. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35063. _super.call(this, name, alpha, beta, radius, target, scene);
  35064. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35065. }
  35066. return AnaglyphArcRotateCamera;
  35067. })(BABYLON.ArcRotateCamera);
  35068. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35069. var AnaglyphGamepadCamera = (function (_super) {
  35070. __extends(AnaglyphGamepadCamera, _super);
  35071. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35072. _super.call(this, name, position, scene);
  35073. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35074. }
  35075. return AnaglyphGamepadCamera;
  35076. })(BABYLON.GamepadCamera);
  35077. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35078. var StereoscopicFreeCamera = (function (_super) {
  35079. __extends(StereoscopicFreeCamera, _super);
  35080. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35081. _super.call(this, name, position, scene);
  35082. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35083. }
  35084. return StereoscopicFreeCamera;
  35085. })(BABYLON.FreeCamera);
  35086. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35087. var StereoscopicArcRotateCamera = (function (_super) {
  35088. __extends(StereoscopicArcRotateCamera, _super);
  35089. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35090. _super.call(this, name, alpha, beta, radius, target, scene);
  35091. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35092. }
  35093. return StereoscopicArcRotateCamera;
  35094. })(BABYLON.ArcRotateCamera);
  35095. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35096. var StereoscopicGamepadCamera = (function (_super) {
  35097. __extends(StereoscopicGamepadCamera, _super);
  35098. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35099. _super.call(this, name, position, scene);
  35100. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35101. }
  35102. return StereoscopicGamepadCamera;
  35103. })(BABYLON.GamepadCamera);
  35104. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35105. })(BABYLON || (BABYLON = {}));
  35106. var BABYLON;
  35107. (function (BABYLON) {
  35108. var HDRRenderingPipeline = (function (_super) {
  35109. __extends(HDRRenderingPipeline, _super);
  35110. /**
  35111. * @constructor
  35112. * @param {string} name - The rendering pipeline name
  35113. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35114. * @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)
  35115. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35116. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35117. */
  35118. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35119. var _this = this;
  35120. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35121. _super.call(this, scene.getEngine(), name);
  35122. /**
  35123. * Public members
  35124. */
  35125. // Gaussian Blur
  35126. /**
  35127. * Gaussian blur coefficient
  35128. * @type {number}
  35129. */
  35130. this.gaussCoeff = 0.3;
  35131. /**
  35132. * Gaussian blur mean
  35133. * @type {number}
  35134. */
  35135. this.gaussMean = 1.0;
  35136. /**
  35137. * Gaussian blur standard deviation
  35138. * @type {number}
  35139. */
  35140. this.gaussStandDev = 0.8;
  35141. /**
  35142. * Gaussian blur multiplier. Multiplies the blur effect
  35143. * @type {number}
  35144. */
  35145. this.gaussMultiplier = 4.0;
  35146. // HDR
  35147. /**
  35148. * Exposure, controls the overall intensity of the pipeline
  35149. * @type {number}
  35150. */
  35151. this.exposure = 1.0;
  35152. /**
  35153. * Minimum luminance that the post-process can output. Luminance is >= 0
  35154. * @type {number}
  35155. */
  35156. this.minimumLuminance = 1.0;
  35157. /**
  35158. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35159. * @type {number}
  35160. */
  35161. this.maximumLuminance = 1e20;
  35162. /**
  35163. * Increase rate for luminance: eye adaptation speed to dark
  35164. * @type {number}
  35165. */
  35166. this.luminanceIncreaserate = 0.5;
  35167. /**
  35168. * Decrease rate for luminance: eye adaptation speed to bright
  35169. * @type {number}
  35170. */
  35171. this.luminanceDecreaseRate = 0.5;
  35172. // Bright pass
  35173. /**
  35174. * Minimum luminance needed to compute HDR
  35175. * @type {number}
  35176. */
  35177. this.brightThreshold = 0.8;
  35178. this._needUpdate = true;
  35179. this._scene = scene;
  35180. // Bright pass
  35181. this._createBrightPassPostProcess(scene, ratio);
  35182. // Down sample X4
  35183. this._createDownSampleX4PostProcess(scene, ratio);
  35184. // Create gaussian blur post-processes
  35185. this._createGaussianBlurPostProcess(scene, ratio);
  35186. // Texture adder
  35187. this._createTextureAdderPostProcess(scene, ratio);
  35188. // Luminance generator
  35189. this._createLuminanceGeneratorPostProcess(scene);
  35190. // HDR
  35191. this._createHDRPostProcess(scene, ratio);
  35192. // Pass postprocess
  35193. if (originalPostProcess === null) {
  35194. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35195. }
  35196. else {
  35197. this._originalPostProcess = originalPostProcess;
  35198. }
  35199. // Configure pipeline
  35200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35203. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35206. var addDownSamplerPostProcess = function (id) {
  35207. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35208. };
  35209. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35210. addDownSamplerPostProcess(i);
  35211. }
  35212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35213. // Finish
  35214. scene.postProcessRenderPipelineManager.addPipeline(this);
  35215. if (cameras !== null) {
  35216. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35217. }
  35218. this.update();
  35219. }
  35220. /**
  35221. * Tells the pipeline to update its post-processes
  35222. */
  35223. HDRRenderingPipeline.prototype.update = function () {
  35224. this._needUpdate = true;
  35225. };
  35226. /**
  35227. * Returns the current calculated luminance
  35228. */
  35229. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35230. return this._hdrCurrentLuminance;
  35231. };
  35232. /**
  35233. * Returns the currently drawn luminance
  35234. */
  35235. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35236. return this._hdrOutputLuminance;
  35237. };
  35238. /**
  35239. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35240. */
  35241. HDRRenderingPipeline.prototype.dispose = function () {
  35242. this._originalPostProcess = undefined;
  35243. this._brightPassPostProcess = undefined;
  35244. this._downSampleX4PostProcess = undefined;
  35245. this._guassianBlurHPostProcess = undefined;
  35246. this._guassianBlurVPostProcess = undefined;
  35247. this._textureAdderPostProcess = undefined;
  35248. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35249. this._downSamplePostProcesses[i] = undefined;
  35250. }
  35251. this._hdrPostProcess = undefined;
  35252. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35253. };
  35254. /**
  35255. * Creates the HDR post-process and computes the luminance adaptation
  35256. */
  35257. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35258. var _this = this;
  35259. var hdrLastLuminance = 0.0;
  35260. this._hdrOutputLuminance = -1.0;
  35261. this._hdrCurrentLuminance = 1.0;
  35262. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35263. this._hdrPostProcess.onApply = function (effect) {
  35264. if (_this._hdrOutputLuminance < 0.0) {
  35265. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35266. }
  35267. else {
  35268. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35269. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35270. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35271. }
  35272. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35273. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35274. }
  35275. else {
  35276. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35277. }
  35278. }
  35279. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35280. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35281. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35282. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35283. effect.setFloat("exposure", _this.exposure);
  35284. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35285. _this._needUpdate = false;
  35286. };
  35287. };
  35288. /**
  35289. * Texture Adder post-process
  35290. */
  35291. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35292. var _this = this;
  35293. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35294. this._textureAdderPostProcess.onApply = function (effect) {
  35295. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35296. };
  35297. };
  35298. /**
  35299. * Down sample X4 post-process
  35300. */
  35301. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35302. var _this = this;
  35303. var downSampleX4Offsets = new Array(32);
  35304. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35305. this._downSampleX4PostProcess.onApply = function (effect) {
  35306. if (_this._needUpdate) {
  35307. var id = 0;
  35308. for (var i = -2; i < 2; i++) {
  35309. for (var j = -2; j < 2; j++) {
  35310. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35311. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35312. id += 2;
  35313. }
  35314. }
  35315. }
  35316. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35317. };
  35318. };
  35319. /**
  35320. * Bright pass post-process
  35321. */
  35322. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35323. var _this = this;
  35324. var brightOffsets = new Array(8);
  35325. var brightPassCallback = function (effect) {
  35326. if (_this._needUpdate) {
  35327. var sU = (1.0 / _this._brightPassPostProcess.width);
  35328. var sV = (1.0 / _this._brightPassPostProcess.height);
  35329. brightOffsets[0] = -0.5 * sU;
  35330. brightOffsets[1] = 0.5 * sV;
  35331. brightOffsets[2] = 0.5 * sU;
  35332. brightOffsets[3] = 0.5 * sV;
  35333. brightOffsets[4] = -0.5 * sU;
  35334. brightOffsets[5] = -0.5 * sV;
  35335. brightOffsets[6] = 0.5 * sU;
  35336. brightOffsets[7] = -0.5 * sV;
  35337. }
  35338. effect.setArray2("dsOffsets", brightOffsets);
  35339. effect.setFloat("brightThreshold", _this.brightThreshold);
  35340. };
  35341. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35342. this._brightPassPostProcess.onApply = brightPassCallback;
  35343. };
  35344. /**
  35345. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35346. */
  35347. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35348. var _this = this;
  35349. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35350. var luminanceOffsets = new Array(8);
  35351. var downSampleOffsets = new Array(18);
  35352. var halfDestPixelSize;
  35353. this._downSamplePostProcesses = new Array(lumSteps);
  35354. // Utils for luminance
  35355. var luminanceUpdateSourceOffsets = function (width, height) {
  35356. var sU = (1.0 / width);
  35357. var sV = (1.0 / height);
  35358. luminanceOffsets[0] = -0.5 * sU;
  35359. luminanceOffsets[1] = 0.5 * sV;
  35360. luminanceOffsets[2] = 0.5 * sU;
  35361. luminanceOffsets[3] = 0.5 * sV;
  35362. luminanceOffsets[4] = -0.5 * sU;
  35363. luminanceOffsets[5] = -0.5 * sV;
  35364. luminanceOffsets[6] = 0.5 * sU;
  35365. luminanceOffsets[7] = -0.5 * sV;
  35366. };
  35367. var luminanceUpdateDestOffsets = function (width, height) {
  35368. var id = 0;
  35369. for (var x = -1; x < 2; x++) {
  35370. for (var y = -1; y < 2; y++) {
  35371. downSampleOffsets[id] = (x) / width;
  35372. downSampleOffsets[id + 1] = (y) / height;
  35373. id += 2;
  35374. }
  35375. }
  35376. };
  35377. // Luminance callback
  35378. var luminanceCallback = function (effect) {
  35379. if (_this._needUpdate) {
  35380. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35381. }
  35382. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35383. effect.setArray2("lumOffsets", luminanceOffsets);
  35384. };
  35385. // Down sample callbacks
  35386. var downSampleCallback = function (indice) {
  35387. var i = indice;
  35388. return function (effect) {
  35389. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35390. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35391. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35392. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35393. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35394. effect.setArray2("dsOffsets", downSampleOffsets);
  35395. };
  35396. };
  35397. var downSampleAfterRenderCallback = function (effect) {
  35398. // Unpack result
  35399. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35400. 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);
  35401. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35402. };
  35403. // Create luminance post-process
  35404. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35405. 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);
  35406. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35407. // Create down sample post-processes
  35408. for (var i = lumSteps - 2; i >= 0; i--) {
  35409. var length = Math.pow(3, i);
  35410. ratio = { width: length, height: length };
  35411. var defines = "#define DOWN_SAMPLE\n";
  35412. if (i === 0) {
  35413. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35414. }
  35415. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35416. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35417. if (i === 0) {
  35418. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35419. }
  35420. }
  35421. };
  35422. /**
  35423. * Gaussian blur post-processes. Horizontal and Vertical
  35424. */
  35425. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35426. var _this = this;
  35427. var blurOffsetsW = new Array(9);
  35428. var blurOffsetsH = new Array(9);
  35429. var blurWeights = new Array(9);
  35430. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35431. // Utils for gaussian blur
  35432. var calculateBlurOffsets = function (height) {
  35433. var lastOutputDimensions = {
  35434. width: scene.getEngine().getRenderWidth(),
  35435. height: scene.getEngine().getRenderHeight()
  35436. };
  35437. for (var i = 0; i < 9; i++) {
  35438. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35439. if (height) {
  35440. blurOffsetsH[i] = value;
  35441. }
  35442. else {
  35443. blurOffsetsW[i] = value;
  35444. }
  35445. }
  35446. };
  35447. var calculateWeights = function () {
  35448. var x = 0.0;
  35449. for (var i = 0; i < 9; i++) {
  35450. x = (i - 4.0) / 4.0;
  35451. 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));
  35452. }
  35453. };
  35454. // Callback
  35455. var gaussianBlurCallback = function (height) {
  35456. return function (effect) {
  35457. if (_this._needUpdate) {
  35458. calculateWeights();
  35459. calculateBlurOffsets(height);
  35460. }
  35461. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35462. effect.setArray("blurWeights", blurWeights);
  35463. effect.setFloat("multiplier", _this.gaussMultiplier);
  35464. };
  35465. };
  35466. // Create horizontal gaussian blur post-processes
  35467. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35468. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35469. // Create vertical gaussian blur post-process
  35470. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35471. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35472. };
  35473. // Luminance generator
  35474. HDRRenderingPipeline.LUM_STEPS = 6;
  35475. return HDRRenderingPipeline;
  35476. })(BABYLON.PostProcessRenderPipeline);
  35477. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35478. })(BABYLON || (BABYLON = {}));
  35479. var BABYLON;
  35480. (function (BABYLON) {
  35481. var FaceAdjacencies = (function () {
  35482. function FaceAdjacencies() {
  35483. this.edges = new Array();
  35484. this.edgesConnectedCount = 0;
  35485. }
  35486. return FaceAdjacencies;
  35487. })();
  35488. var EdgesRenderer = (function () {
  35489. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35490. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35491. if (epsilon === void 0) { epsilon = 0.95; }
  35492. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35493. this._linesPositions = new Array();
  35494. this._linesNormals = new Array();
  35495. this._linesIndices = new Array();
  35496. this._buffers = new Array();
  35497. this._checkVerticesInsteadOfIndices = false;
  35498. this._source = source;
  35499. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35500. this._epsilon = epsilon;
  35501. this._prepareRessources();
  35502. this._generateEdgesLines();
  35503. }
  35504. EdgesRenderer.prototype._prepareRessources = function () {
  35505. if (this._lineShader) {
  35506. return;
  35507. }
  35508. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35509. attributes: ["position", "normal"],
  35510. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35511. });
  35512. this._lineShader.disableDepthWrite = true;
  35513. this._lineShader.backFaceCulling = false;
  35514. };
  35515. EdgesRenderer.prototype.dispose = function () {
  35516. this._vb0.dispose();
  35517. this._vb1.dispose();
  35518. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35519. this._lineShader.dispose();
  35520. };
  35521. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35522. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35523. return 0;
  35524. }
  35525. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35526. return 1;
  35527. }
  35528. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35529. return 2;
  35530. }
  35531. return -1;
  35532. };
  35533. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35534. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35535. return 0;
  35536. }
  35537. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35538. return 1;
  35539. }
  35540. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35541. return 2;
  35542. }
  35543. return -1;
  35544. };
  35545. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35546. var needToCreateLine;
  35547. if (edge === undefined) {
  35548. needToCreateLine = true;
  35549. }
  35550. else {
  35551. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35552. needToCreateLine = dotProduct < this._epsilon;
  35553. }
  35554. if (needToCreateLine) {
  35555. var offset = this._linesPositions.length / 3;
  35556. var normal = p0.subtract(p1);
  35557. normal.normalize();
  35558. // Positions
  35559. this._linesPositions.push(p0.x);
  35560. this._linesPositions.push(p0.y);
  35561. this._linesPositions.push(p0.z);
  35562. this._linesPositions.push(p0.x);
  35563. this._linesPositions.push(p0.y);
  35564. this._linesPositions.push(p0.z);
  35565. this._linesPositions.push(p1.x);
  35566. this._linesPositions.push(p1.y);
  35567. this._linesPositions.push(p1.z);
  35568. this._linesPositions.push(p1.x);
  35569. this._linesPositions.push(p1.y);
  35570. this._linesPositions.push(p1.z);
  35571. // Normals
  35572. this._linesNormals.push(p1.x);
  35573. this._linesNormals.push(p1.y);
  35574. this._linesNormals.push(p1.z);
  35575. this._linesNormals.push(-1);
  35576. this._linesNormals.push(p1.x);
  35577. this._linesNormals.push(p1.y);
  35578. this._linesNormals.push(p1.z);
  35579. this._linesNormals.push(1);
  35580. this._linesNormals.push(p0.x);
  35581. this._linesNormals.push(p0.y);
  35582. this._linesNormals.push(p0.z);
  35583. this._linesNormals.push(-1);
  35584. this._linesNormals.push(p0.x);
  35585. this._linesNormals.push(p0.y);
  35586. this._linesNormals.push(p0.z);
  35587. this._linesNormals.push(1);
  35588. // Indices
  35589. this._linesIndices.push(offset);
  35590. this._linesIndices.push(offset + 1);
  35591. this._linesIndices.push(offset + 2);
  35592. this._linesIndices.push(offset);
  35593. this._linesIndices.push(offset + 2);
  35594. this._linesIndices.push(offset + 3);
  35595. }
  35596. };
  35597. EdgesRenderer.prototype._generateEdgesLines = function () {
  35598. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35599. var indices = this._source.getIndices();
  35600. // First let's find adjacencies
  35601. var adjacencies = new Array();
  35602. var faceNormals = new Array();
  35603. var index;
  35604. var faceAdjacencies;
  35605. // Prepare faces
  35606. for (index = 0; index < indices.length; index += 3) {
  35607. faceAdjacencies = new FaceAdjacencies();
  35608. var p0Index = indices[index];
  35609. var p1Index = indices[index + 1];
  35610. var p2Index = indices[index + 2];
  35611. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35612. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35613. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35614. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35615. faceNormal.normalize();
  35616. faceNormals.push(faceNormal);
  35617. adjacencies.push(faceAdjacencies);
  35618. }
  35619. // Scan
  35620. for (index = 0; index < adjacencies.length; index++) {
  35621. faceAdjacencies = adjacencies[index];
  35622. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35623. var otherFaceAdjacencies = adjacencies[otherIndex];
  35624. if (faceAdjacencies.edgesConnectedCount === 3) {
  35625. break;
  35626. }
  35627. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35628. continue;
  35629. }
  35630. var otherP0 = indices[otherIndex * 3];
  35631. var otherP1 = indices[otherIndex * 3 + 1];
  35632. var otherP2 = indices[otherIndex * 3 + 2];
  35633. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35634. var otherEdgeIndex;
  35635. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35636. continue;
  35637. }
  35638. switch (edgeIndex) {
  35639. case 0:
  35640. if (this._checkVerticesInsteadOfIndices) {
  35641. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35642. }
  35643. else {
  35644. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35645. }
  35646. break;
  35647. case 1:
  35648. if (this._checkVerticesInsteadOfIndices) {
  35649. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35650. }
  35651. else {
  35652. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35653. }
  35654. break;
  35655. case 2:
  35656. if (this._checkVerticesInsteadOfIndices) {
  35657. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35658. }
  35659. else {
  35660. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35661. }
  35662. break;
  35663. }
  35664. if (otherEdgeIndex === -1) {
  35665. continue;
  35666. }
  35667. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35668. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35669. faceAdjacencies.edgesConnectedCount++;
  35670. otherFaceAdjacencies.edgesConnectedCount++;
  35671. if (faceAdjacencies.edgesConnectedCount === 3) {
  35672. break;
  35673. }
  35674. }
  35675. }
  35676. }
  35677. // Create lines
  35678. for (index = 0; index < adjacencies.length; index++) {
  35679. // 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
  35680. var current = adjacencies[index];
  35681. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35682. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35683. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35684. }
  35685. // Merge into a single mesh
  35686. var engine = this._source.getScene().getEngine();
  35687. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35688. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35689. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35690. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35691. this._ib = engine.createIndexBuffer(this._linesIndices);
  35692. this._indicesCount = this._linesIndices.length;
  35693. };
  35694. EdgesRenderer.prototype.render = function () {
  35695. if (!this._lineShader.isReady()) {
  35696. return;
  35697. }
  35698. var scene = this._source.getScene();
  35699. var engine = scene.getEngine();
  35700. this._lineShader._preBind();
  35701. // VBOs
  35702. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35703. scene.resetCachedMaterial();
  35704. this._lineShader.setColor4("color", this._source.edgesColor);
  35705. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35706. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35707. this._lineShader.bind(this._source.getWorldMatrix());
  35708. // Draw order
  35709. engine.draw(true, 0, this._indicesCount);
  35710. this._lineShader.unbind();
  35711. engine.setDepthWrite(true);
  35712. };
  35713. return EdgesRenderer;
  35714. })();
  35715. BABYLON.EdgesRenderer = EdgesRenderer;
  35716. })(BABYLON || (BABYLON = {}));
  35717. var BABYLON;
  35718. (function (BABYLON) {
  35719. (function (TonemappingOperator) {
  35720. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35721. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35722. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35723. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35724. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35725. var TonemappingOperator = BABYLON.TonemappingOperator;
  35726. ;
  35727. var TonemapPostProcess = (function (_super) {
  35728. __extends(TonemapPostProcess, _super);
  35729. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35730. var _this = this;
  35731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35732. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35733. this._operator = operator;
  35734. this._exposureAdjustment = exposureAdjustment;
  35735. var params = ["_ExposureAdjustment"];
  35736. var defines = "#define ";
  35737. if (operator === TonemappingOperator.Hable)
  35738. defines += "HABLE_TONEMAPPING";
  35739. else if (operator === TonemappingOperator.Reinhard)
  35740. defines += "REINHARD_TONEMAPPING";
  35741. else if (operator === TonemappingOperator.HejiDawson)
  35742. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35743. else if (operator === TonemappingOperator.Photographic)
  35744. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35745. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35746. this.onApply = function (effect) {
  35747. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35748. };
  35749. }
  35750. return TonemapPostProcess;
  35751. })(BABYLON.PostProcess);
  35752. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35753. })(BABYLON || (BABYLON = {}));
  35754. var BABYLON;
  35755. (function (BABYLON) {
  35756. var ReflectionProbe = (function () {
  35757. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35758. var _this = this;
  35759. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35760. this.name = name;
  35761. this._viewMatrix = BABYLON.Matrix.Identity();
  35762. this._target = BABYLON.Vector3.Zero();
  35763. this._add = BABYLON.Vector3.Zero();
  35764. this.position = BABYLON.Vector3.Zero();
  35765. this._scene = scene;
  35766. this._scene.reflectionProbes.push(this);
  35767. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35768. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35769. switch (faceIndex) {
  35770. case 0:
  35771. _this._add.copyFromFloats(1, 0, 0);
  35772. break;
  35773. case 1:
  35774. _this._add.copyFromFloats(-1, 0, 0);
  35775. break;
  35776. case 2:
  35777. _this._add.copyFromFloats(0, -1, 0);
  35778. break;
  35779. case 3:
  35780. _this._add.copyFromFloats(0, 1, 0);
  35781. break;
  35782. case 4:
  35783. _this._add.copyFromFloats(0, 0, 1);
  35784. break;
  35785. case 5:
  35786. _this._add.copyFromFloats(0, 0, -1);
  35787. break;
  35788. }
  35789. if (_this._attachedMesh) {
  35790. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35791. }
  35792. _this.position.addToRef(_this._add, _this._target);
  35793. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35794. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35795. };
  35796. this._renderTargetTexture.onAfterUnbind = function () {
  35797. scene.updateTransformMatrix(true);
  35798. };
  35799. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35800. }
  35801. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35802. get: function () {
  35803. return this._renderTargetTexture.refreshRate;
  35804. },
  35805. set: function (value) {
  35806. this._renderTargetTexture.refreshRate = value;
  35807. },
  35808. enumerable: true,
  35809. configurable: true
  35810. });
  35811. ReflectionProbe.prototype.getScene = function () {
  35812. return this._scene;
  35813. };
  35814. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35815. get: function () {
  35816. return this._renderTargetTexture;
  35817. },
  35818. enumerable: true,
  35819. configurable: true
  35820. });
  35821. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35822. get: function () {
  35823. return this._renderTargetTexture.renderList;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35829. this._attachedMesh = mesh;
  35830. };
  35831. ReflectionProbe.prototype.dispose = function () {
  35832. var index = this._scene.reflectionProbes.indexOf(this);
  35833. if (index !== -1) {
  35834. // Remove from the scene if found
  35835. this._scene.reflectionProbes.splice(index, 1);
  35836. }
  35837. };
  35838. return ReflectionProbe;
  35839. })();
  35840. BABYLON.ReflectionProbe = ReflectionProbe;
  35841. })(BABYLON || (BABYLON = {}));
  35842. var BABYLON;
  35843. (function (BABYLON) {
  35844. var SolidParticle = (function () {
  35845. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35846. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35847. this.position = BABYLON.Vector3.Zero(); // position
  35848. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35849. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35850. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35851. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35852. this.alive = true; // alive
  35853. this.idx = particleIndex;
  35854. this._pos = positionIndex;
  35855. this._model = model;
  35856. this.shapeId = shapeId;
  35857. this.idxInShape = idxInShape;
  35858. }
  35859. return SolidParticle;
  35860. })();
  35861. BABYLON.SolidParticle = SolidParticle;
  35862. var ModelShape = (function () {
  35863. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35864. this.shapeID = id;
  35865. this._shape = shape;
  35866. this._shapeUV = shapeUV;
  35867. this._positionFunction = posFunction;
  35868. this._vertexFunction = vtxFunction;
  35869. }
  35870. return ModelShape;
  35871. })();
  35872. BABYLON.ModelShape = ModelShape;
  35873. })(BABYLON || (BABYLON = {}));
  35874. var BABYLON;
  35875. (function (BABYLON) {
  35876. var SolidParticleSystem = (function () {
  35877. function SolidParticleSystem(name, scene, options) {
  35878. // public members
  35879. this.particles = new Array();
  35880. this.nbParticles = 0;
  35881. this.billboard = false;
  35882. this.counter = 0;
  35883. this.vars = {};
  35884. this._positions = new Array();
  35885. this._indices = new Array();
  35886. this._normals = new Array();
  35887. this._colors = new Array();
  35888. this._uvs = new Array();
  35889. this._index = 0; // indices index
  35890. this._updatable = true;
  35891. this._pickable = false;
  35892. this._alwaysVisible = false;
  35893. this._shapeCounter = 0;
  35894. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35895. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35896. this._computeParticleColor = true;
  35897. this._computeParticleTexture = true;
  35898. this._computeParticleRotation = true;
  35899. this._computeParticleVertex = false;
  35900. this._cam_axisZ = BABYLON.Vector3.Zero();
  35901. this._cam_axisY = BABYLON.Vector3.Zero();
  35902. this._cam_axisX = BABYLON.Vector3.Zero();
  35903. this._axisX = BABYLON.Axis.X;
  35904. this._axisY = BABYLON.Axis.Y;
  35905. this._axisZ = BABYLON.Axis.Z;
  35906. this._fakeCamPos = BABYLON.Vector3.Zero();
  35907. this._rotMatrix = new BABYLON.Matrix();
  35908. this._invertMatrix = new BABYLON.Matrix();
  35909. this._rotated = BABYLON.Vector3.Zero();
  35910. this._quaternion = new BABYLON.Quaternion();
  35911. this._vertex = BABYLON.Vector3.Zero();
  35912. this._normal = BABYLON.Vector3.Zero();
  35913. this._yaw = 0.0;
  35914. this._pitch = 0.0;
  35915. this._roll = 0.0;
  35916. this._halfroll = 0.0;
  35917. this._halfpitch = 0.0;
  35918. this._halfyaw = 0.0;
  35919. this._sinRoll = 0.0;
  35920. this._cosRoll = 0.0;
  35921. this._sinPitch = 0.0;
  35922. this._cosPitch = 0.0;
  35923. this._sinYaw = 0.0;
  35924. this._cosYaw = 0.0;
  35925. this._w = 0.0;
  35926. this.name = name;
  35927. this._scene = scene;
  35928. this._camera = scene.activeCamera;
  35929. this._pickable = options ? options.isPickable : false;
  35930. if (options && options.updatable) {
  35931. this._updatable = options.updatable;
  35932. }
  35933. else {
  35934. this._updatable = true;
  35935. }
  35936. if (this._pickable) {
  35937. this.pickedParticles = [];
  35938. }
  35939. }
  35940. // build the SPS mesh : returns the mesh
  35941. SolidParticleSystem.prototype.buildMesh = function () {
  35942. if (this.nbParticles === 0) {
  35943. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35944. this.addShape(triangle, 1);
  35945. triangle.dispose();
  35946. }
  35947. this._positions32 = new Float32Array(this._positions);
  35948. this._uvs32 = new Float32Array(this._uvs);
  35949. this._colors32 = new Float32Array(this._colors);
  35950. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35951. this._normals32 = new Float32Array(this._normals);
  35952. this._fixedNormal32 = new Float32Array(this._normals);
  35953. var vertexData = new BABYLON.VertexData();
  35954. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35955. vertexData.indices = this._indices;
  35956. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35957. if (this._uvs32) {
  35958. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35959. ;
  35960. }
  35961. if (this._colors32) {
  35962. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35963. }
  35964. var mesh = new BABYLON.Mesh(name, this._scene);
  35965. vertexData.applyToMesh(mesh, this._updatable);
  35966. this.mesh = mesh;
  35967. this.mesh.isPickable = this._pickable;
  35968. // free memory
  35969. this._positions = null;
  35970. this._normals = null;
  35971. this._uvs = null;
  35972. this._colors = null;
  35973. if (!this._updatable) {
  35974. this.particles.length = 0;
  35975. }
  35976. return mesh;
  35977. };
  35978. //reset copy
  35979. SolidParticleSystem.prototype._resetCopy = function () {
  35980. this._copy.position.x = 0;
  35981. this._copy.position.y = 0;
  35982. this._copy.position.z = 0;
  35983. this._copy.rotation.x = 0;
  35984. this._copy.rotation.y = 0;
  35985. this._copy.rotation.z = 0;
  35986. this._copy.quaternion = null;
  35987. this._copy.scale.x = 1;
  35988. this._copy.scale.y = 1;
  35989. this._copy.scale.z = 1;
  35990. this._copy.uvs.x = 0;
  35991. this._copy.uvs.y = 0;
  35992. this._copy.uvs.z = 1;
  35993. this._copy.uvs.w = 1;
  35994. this._copy.color = null;
  35995. };
  35996. // _meshBuilder : inserts the shape model in the global SPS mesh
  35997. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35998. var i;
  35999. var u = 0;
  36000. var c = 0;
  36001. this._resetCopy();
  36002. if (options && options.positionFunction) {
  36003. options.positionFunction(this._copy, idx, idxInShape);
  36004. }
  36005. if (this._copy.quaternion) {
  36006. this._quaternion.x = this._copy.quaternion.x;
  36007. this._quaternion.y = this._copy.quaternion.y;
  36008. this._quaternion.z = this._copy.quaternion.z;
  36009. this._quaternion.w = this._copy.quaternion.w;
  36010. }
  36011. else {
  36012. this._yaw = this._copy.rotation.y;
  36013. this._pitch = this._copy.rotation.x;
  36014. this._roll = this._copy.rotation.z;
  36015. this._quaternionRotationYPR();
  36016. }
  36017. this._quaternionToRotationMatrix();
  36018. for (i = 0; i < shape.length; i++) {
  36019. this._vertex.x = shape[i].x;
  36020. this._vertex.y = shape[i].y;
  36021. this._vertex.z = shape[i].z;
  36022. if (options && options.vertexFunction) {
  36023. options.vertexFunction(this._copy, this._vertex, i);
  36024. }
  36025. this._vertex.x *= this._copy.scale.x;
  36026. this._vertex.y *= this._copy.scale.y;
  36027. this._vertex.z *= this._copy.scale.z;
  36028. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36029. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36030. if (meshUV) {
  36031. 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);
  36032. u += 2;
  36033. }
  36034. if (this._copy.color) {
  36035. this._color = this._copy.color;
  36036. }
  36037. else if (meshCol && meshCol[c]) {
  36038. this._color.r = meshCol[c];
  36039. this._color.g = meshCol[c + 1];
  36040. this._color.b = meshCol[c + 2];
  36041. this._color.a = meshCol[c + 3];
  36042. }
  36043. else {
  36044. this._color.r = 1;
  36045. this._color.g = 1;
  36046. this._color.b = 1;
  36047. this._color.a = 1;
  36048. }
  36049. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36050. c += 4;
  36051. }
  36052. for (i = 0; i < meshInd.length; i++) {
  36053. indices.push(p + meshInd[i]);
  36054. }
  36055. if (this._pickable) {
  36056. var nbfaces = meshInd.length / 3;
  36057. for (i = 0; i < nbfaces; i++) {
  36058. this.pickedParticles.push({ idx: idx, faceId: i });
  36059. }
  36060. }
  36061. };
  36062. // returns a shape array from positions array
  36063. SolidParticleSystem.prototype._posToShape = function (positions) {
  36064. var shape = [];
  36065. for (var i = 0; i < positions.length; i += 3) {
  36066. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36067. }
  36068. return shape;
  36069. };
  36070. // returns a shapeUV array from a Vector4 uvs
  36071. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36072. var shapeUV = [];
  36073. if (uvs) {
  36074. for (var i = 0; i < uvs.length; i++)
  36075. shapeUV.push(uvs[i]);
  36076. }
  36077. return shapeUV;
  36078. };
  36079. // adds a new particle object in the particles array
  36080. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36081. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36082. };
  36083. // add solid particles from a shape model in the particles array
  36084. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36085. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36086. var meshInd = mesh.getIndices();
  36087. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36088. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36089. var shape = this._posToShape(meshPos);
  36090. var shapeUV = this._uvsToShapeUV(meshUV);
  36091. var posfunc = options ? options.positionFunction : null;
  36092. var vtxfunc = options ? options.vertexFunction : null;
  36093. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36094. // particles
  36095. var idx = this.nbParticles;
  36096. for (var i = 0; i < nb; i++) {
  36097. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36098. if (this._updatable) {
  36099. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36100. }
  36101. this._index += shape.length;
  36102. idx++;
  36103. }
  36104. this.nbParticles += nb;
  36105. this._shapeCounter++;
  36106. return this._shapeCounter;
  36107. };
  36108. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36109. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36110. this._resetCopy();
  36111. if (particle._model._positionFunction) {
  36112. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36113. }
  36114. if (this._copy.quaternion) {
  36115. this._quaternion.x = this._copy.quaternion.x;
  36116. this._quaternion.y = this._copy.quaternion.y;
  36117. this._quaternion.z = this._copy.quaternion.z;
  36118. this._quaternion.w = this._copy.quaternion.w;
  36119. }
  36120. else {
  36121. this._yaw = this._copy.rotation.y;
  36122. this._pitch = this._copy.rotation.x;
  36123. this._roll = this._copy.rotation.z;
  36124. this._quaternionRotationYPR();
  36125. }
  36126. this._quaternionToRotationMatrix();
  36127. this._shape = particle._model._shape;
  36128. for (var pt = 0; pt < this._shape.length; pt++) {
  36129. this._vertex.x = this._shape[pt].x;
  36130. this._vertex.y = this._shape[pt].y;
  36131. this._vertex.z = this._shape[pt].z;
  36132. if (particle._model._vertexFunction) {
  36133. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36134. }
  36135. this._vertex.x *= this._copy.scale.x;
  36136. this._vertex.y *= this._copy.scale.y;
  36137. this._vertex.z *= this._copy.scale.z;
  36138. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36139. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36140. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36141. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36142. }
  36143. particle.position.x = 0;
  36144. particle.position.y = 0;
  36145. particle.position.z = 0;
  36146. particle.rotation.x = 0;
  36147. particle.rotation.y = 0;
  36148. particle.rotation.z = 0;
  36149. particle.quaternion = null;
  36150. particle.scale.x = 1;
  36151. particle.scale.y = 1;
  36152. particle.scale.z = 1;
  36153. };
  36154. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36155. SolidParticleSystem.prototype.rebuildMesh = function () {
  36156. for (var p = 0; p < this.particles.length; p++) {
  36157. this._rebuildParticle(this.particles[p]);
  36158. }
  36159. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36160. };
  36161. // sets all the particles : updates the VBO
  36162. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36163. if (start === void 0) { start = 0; }
  36164. if (end === void 0) { end = this.nbParticles - 1; }
  36165. if (update === void 0) { update = true; }
  36166. if (!this._updatable) {
  36167. return;
  36168. }
  36169. // custom beforeUpdate
  36170. this.beforeUpdateParticles(start, end, update);
  36171. this._cam_axisX.x = 1;
  36172. this._cam_axisX.y = 0;
  36173. this._cam_axisX.z = 0;
  36174. this._cam_axisY.x = 0;
  36175. this._cam_axisY.y = 1;
  36176. this._cam_axisY.z = 0;
  36177. this._cam_axisZ.x = 0;
  36178. this._cam_axisZ.y = 0;
  36179. this._cam_axisZ.z = 1;
  36180. // if the particles will always face the camera
  36181. if (this.billboard) {
  36182. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36183. this._yaw = this.mesh.rotation.y;
  36184. this._pitch = this.mesh.rotation.x;
  36185. this._roll = this.mesh.rotation.z;
  36186. this._quaternionRotationYPR();
  36187. this._quaternionToRotationMatrix();
  36188. this._rotMatrix.invertToRef(this._invertMatrix);
  36189. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36190. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36191. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36192. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36193. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36194. this._cam_axisY.normalize();
  36195. this._cam_axisX.normalize();
  36196. this._cam_axisZ.normalize();
  36197. }
  36198. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36199. var idx = 0;
  36200. var index = 0;
  36201. var colidx = 0;
  36202. var colorIndex = 0;
  36203. var uvidx = 0;
  36204. var uvIndex = 0;
  36205. // particle loop
  36206. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36207. for (var p = start; p <= end; p++) {
  36208. this._particle = this.particles[p];
  36209. this._shape = this._particle._model._shape;
  36210. this._shapeUV = this._particle._model._shapeUV;
  36211. // call to custom user function to update the particle properties
  36212. this.updateParticle(this._particle);
  36213. // particle rotation matrix
  36214. if (this.billboard) {
  36215. this._particle.rotation.x = 0.0;
  36216. this._particle.rotation.y = 0.0;
  36217. }
  36218. if (this._computeParticleRotation) {
  36219. if (this._particle.quaternion) {
  36220. this._quaternion.x = this._particle.quaternion.x;
  36221. this._quaternion.y = this._particle.quaternion.y;
  36222. this._quaternion.z = this._particle.quaternion.z;
  36223. this._quaternion.w = this._particle.quaternion.w;
  36224. }
  36225. else {
  36226. this._yaw = this._particle.rotation.y;
  36227. this._pitch = this._particle.rotation.x;
  36228. this._roll = this._particle.rotation.z;
  36229. this._quaternionRotationYPR();
  36230. }
  36231. this._quaternionToRotationMatrix();
  36232. }
  36233. for (var pt = 0; pt < this._shape.length; pt++) {
  36234. idx = index + pt * 3;
  36235. colidx = colorIndex + pt * 4;
  36236. uvidx = uvIndex + pt * 2;
  36237. this._vertex.x = this._shape[pt].x;
  36238. this._vertex.y = this._shape[pt].y;
  36239. this._vertex.z = this._shape[pt].z;
  36240. if (this._computeParticleVertex) {
  36241. this.updateParticleVertex(this._particle, this._vertex, pt);
  36242. }
  36243. // positions
  36244. this._vertex.x *= this._particle.scale.x;
  36245. this._vertex.y *= this._particle.scale.y;
  36246. this._vertex.z *= this._particle.scale.z;
  36247. 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];
  36248. 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;
  36249. 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;
  36250. 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;
  36251. 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;
  36252. 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;
  36253. 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;
  36254. // normals : if the particles can't be morphed then just rotate the normals
  36255. if (!this._computeParticleVertex && !this.billboard) {
  36256. this._normal.x = this._fixedNormal32[idx];
  36257. this._normal.y = this._fixedNormal32[idx + 1];
  36258. this._normal.z = this._fixedNormal32[idx + 2];
  36259. 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];
  36260. 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;
  36261. 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;
  36262. 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;
  36263. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36264. 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;
  36265. 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;
  36266. }
  36267. if (this._computeParticleColor) {
  36268. this._colors32[colidx] = this._particle.color.r;
  36269. this._colors32[colidx + 1] = this._particle.color.g;
  36270. this._colors32[colidx + 2] = this._particle.color.b;
  36271. this._colors32[colidx + 3] = this._particle.color.a;
  36272. }
  36273. if (this._computeParticleTexture) {
  36274. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36275. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36276. }
  36277. }
  36278. index = idx + 3;
  36279. colorIndex = colidx + 4;
  36280. uvIndex = uvidx + 2;
  36281. }
  36282. if (update) {
  36283. if (this._computeParticleColor) {
  36284. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36285. }
  36286. if (this._computeParticleTexture) {
  36287. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36288. }
  36289. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36290. if (!this.mesh.areNormalsFrozen) {
  36291. if (this._computeParticleVertex || this.billboard) {
  36292. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36293. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36294. for (var i = 0; i < this._normals32.length; i++) {
  36295. this._fixedNormal32[i] = this._normals32[i];
  36296. }
  36297. }
  36298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36299. }
  36300. }
  36301. this.afterUpdateParticles(start, end, update);
  36302. };
  36303. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36304. this._halfroll = this._roll * 0.5;
  36305. this._halfpitch = this._pitch * 0.5;
  36306. this._halfyaw = this._yaw * 0.5;
  36307. this._sinRoll = Math.sin(this._halfroll);
  36308. this._cosRoll = Math.cos(this._halfroll);
  36309. this._sinPitch = Math.sin(this._halfpitch);
  36310. this._cosPitch = Math.cos(this._halfpitch);
  36311. this._sinYaw = Math.sin(this._halfyaw);
  36312. this._cosYaw = Math.cos(this._halfyaw);
  36313. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36314. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36315. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36316. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36317. };
  36318. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36319. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36320. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36321. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36322. this._rotMatrix.m[3] = 0;
  36323. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36324. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36325. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36326. this._rotMatrix.m[7] = 0;
  36327. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36328. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36329. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36330. this._rotMatrix.m[11] = 0;
  36331. this._rotMatrix.m[12] = 0;
  36332. this._rotMatrix.m[13] = 0;
  36333. this._rotMatrix.m[14] = 0;
  36334. this._rotMatrix.m[15] = 1.0;
  36335. };
  36336. // dispose the SPS
  36337. SolidParticleSystem.prototype.dispose = function () {
  36338. this.mesh.dispose();
  36339. this.vars = null;
  36340. // drop references to internal big arrays for the GC
  36341. this._positions = null;
  36342. this._indices = null;
  36343. this._normals = null;
  36344. this._uvs = null;
  36345. this._colors = null;
  36346. this._positions32 = null;
  36347. this._normals32 = null;
  36348. this._fixedNormal32 = null;
  36349. this._uvs32 = null;
  36350. this._colors32 = null;
  36351. this.pickedParticles = null;
  36352. };
  36353. // Visibilty helpers
  36354. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36355. this.mesh.refreshBoundingInfo();
  36356. };
  36357. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36358. // getter and setter
  36359. get: function () {
  36360. return this._alwaysVisible;
  36361. },
  36362. set: function (val) {
  36363. this._alwaysVisible = val;
  36364. this.mesh.alwaysSelectAsActiveMesh = val;
  36365. },
  36366. enumerable: true,
  36367. configurable: true
  36368. });
  36369. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36370. // getters
  36371. get: function () {
  36372. return this._computeParticleRotation;
  36373. },
  36374. // Optimizer setters
  36375. set: function (val) {
  36376. this._computeParticleRotation = val;
  36377. },
  36378. enumerable: true,
  36379. configurable: true
  36380. });
  36381. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36382. get: function () {
  36383. return this._computeParticleColor;
  36384. },
  36385. set: function (val) {
  36386. this._computeParticleColor = val;
  36387. },
  36388. enumerable: true,
  36389. configurable: true
  36390. });
  36391. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36392. get: function () {
  36393. return this._computeParticleTexture;
  36394. },
  36395. set: function (val) {
  36396. this._computeParticleTexture = val;
  36397. },
  36398. enumerable: true,
  36399. configurable: true
  36400. });
  36401. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36402. get: function () {
  36403. return this._computeParticleVertex;
  36404. },
  36405. set: function (val) {
  36406. this._computeParticleVertex = val;
  36407. },
  36408. enumerable: true,
  36409. configurable: true
  36410. });
  36411. // =======================================================================
  36412. // Particle behavior logic
  36413. // these following methods may be overwritten by the user to fit his needs
  36414. // init : sets all particles first values and calls updateParticle to set them in space
  36415. // can be overwritten by the user
  36416. SolidParticleSystem.prototype.initParticles = function () {
  36417. };
  36418. // recycles a particle : can by overwritten by the user
  36419. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36420. return particle;
  36421. };
  36422. // updates a particle : can be overwritten by the user
  36423. // will be called on each particle by setParticles() :
  36424. // ex : just set a particle position or velocity and recycle conditions
  36425. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36426. return particle;
  36427. };
  36428. // updates a vertex of a particle : can be overwritten by the user
  36429. // will be called on each vertex particle by setParticles() :
  36430. // particle : the current particle
  36431. // vertex : the current index of the current particle
  36432. // pt : the index of the current vertex in the particle shape
  36433. // ex : just set a vertex particle position
  36434. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36435. return vertex;
  36436. };
  36437. // will be called before any other treatment by setParticles()
  36438. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36439. };
  36440. // will be called after all setParticles() treatments
  36441. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36442. };
  36443. return SolidParticleSystem;
  36444. })();
  36445. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36446. })(BABYLON || (BABYLON = {}));
  36447. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","bricktexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"precision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#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 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#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\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 BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firetexturePixelShader":"precision highp float;\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grasstexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","marbletexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  36448. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,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 i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.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)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(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);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=n;var r=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,f=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,f)},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=r;var o=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 e(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),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,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,f=t.y*a+r.y*u+n.y*m+o.y*y,p=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,f,p)},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,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,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=c.X,f=c.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,f)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,f)<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=o;var s=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=s;var e=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=o.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,f=y+c;return 0!==f&&1!==f?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*f),t.z=Math.atan2(e-h,u+m)):0===f?(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],f=o+a+c;f>0?(n=.5/Math.sqrt(f+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=e;var h=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],f=this.m[12],p=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*p,v=m*l-y*p,g=u*x-c*f,d=u*l-y*f,T=u*p-m*f,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),A=1/(i*R+n*_+r*M+o*F),b=h*x-a*l,P=e*x-a*p,C=e*l-h*p,I=s*x-a*f,E=s*l-h*f,q=s*p-e*f,L=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*A,t.m[4]=_*A,t.m[8]=M*A,t.m[12]=F*A,t.m[1]=-(n*z-r*w+o*v)*A,t.m[5]=(i*z-r*g+o*d)*A,t.m[9]=-(i*w-n*g+o*T)*A,t.m[13]=(i*v-n*d+r*T)*A,t.m[2]=(n*b-r*P+o*C)*A,t.m[6]=-(i*b-r*I+o*E)*A,t.m[10]=(i*P-n*I+o*q)*A,t.m[14]=-(i*C-n*E+r*q)*A,t.m[3]=-(n*L-r*D+o*S)*A,t.m[7]=(i*L-r*Z+o*N)*A,t.m[11]=-(i*D-n*Z+o*W)*A,t.m[15]=(i*S-n*N+r*W)*A,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],f=this.m[10],p=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],A=t.m[8],b=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],q=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*A+e*I,i[n+1]=r*g+o*_+s*b+e*E,i[n+2]=r*d+o*M+s*P+e*q,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*A+m*I,i[n+5]=h*g+a*_+u*b+m*E,i[n+6]=h*d+a*M+u*P+m*q,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+f*A+p*I,i[n+9]=y*g+c*_+f*b+p*E,i[n+10]=y*d+c*M+f*P+p*q,i[n+11]=y*T+c*F+f*C+p*L,i[n+12]=l*v+x*R+z*A+w*I,i[n+13]=l*g+x*_+z*b+w*E,i[n+14]=l*d+x*M+z*P+w*q,i[n+15]=l*T+x*F+z*C+w*L,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,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=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=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*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 e.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,f,p,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]=f,x.m[14]=p,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,f,p,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]=f,z.m[13]=p,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,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){e.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){\nr.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},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 e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(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=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=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(a,u,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,f=Math.sqrt(m*m+y*y+c*c);return r=0!==f?1/f: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=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.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 o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(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=m;var y=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=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.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=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=c;var f=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,f=1/(3*s*m+2*e*a+h);a-=(c-t)*f,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=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var p=t.Orientation,l=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=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-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 r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.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?p.CW:p.CCW,this.angle=l.FromDegrees(this.orientation===p.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,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 r(i,n),u=new r(o,s),m=new x(h,a,u),y=m.angle.radians()/e;m.orientation===p.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,f=0;e>f;f++){var l=Math.cos(c)*m.radius+m.centerPoint.x,z=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(l,z),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.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var y=u.normalize(),c=n-o;return new r(h.x+y.x*c,h.y+y.y*c)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=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]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.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 s;if(void 0===r||null===r){var e;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)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=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;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e: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;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,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=g;var d=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var T=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.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=T}(BABYLON||(BABYLON={}));";
  36449. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36450. module.exports = BABYLON;
  36451. };