babylon.max.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847
  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. // Unbind
  6410. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6411. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6412. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6413. texture._framebuffer = framebuffer;
  6414. texture._depthBuffer = depthBuffer;
  6415. this.resetTextureCache();
  6416. texture._width = size;
  6417. texture._height = size;
  6418. texture.isReady = true;
  6419. return texture;
  6420. };
  6421. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6422. var _this = this;
  6423. var gl = this._gl;
  6424. var texture = gl.createTexture();
  6425. texture.isCube = true;
  6426. texture.url = rootUrl;
  6427. texture.references = 1;
  6428. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6429. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6430. if (isDDS) {
  6431. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6432. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6433. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6434. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6435. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6436. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6437. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6438. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6439. }
  6440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6444. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6445. _this.resetTextureCache();
  6446. texture._width = info.width;
  6447. texture._height = info.height;
  6448. texture.isReady = true;
  6449. }, null, null, true);
  6450. }
  6451. else {
  6452. cascadeLoad(rootUrl, scene, function (imgs) {
  6453. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6454. var height = width;
  6455. _this._prepareWorkingCanvas();
  6456. _this._workingCanvas.width = width;
  6457. _this._workingCanvas.height = height;
  6458. var faces = [
  6459. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6460. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6461. ];
  6462. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6463. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6464. for (var index = 0; index < faces.length; index++) {
  6465. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6466. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6467. }
  6468. if (!noMipmap) {
  6469. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6470. }
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6475. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6476. _this.resetTextureCache();
  6477. texture._width = width;
  6478. texture._height = height;
  6479. texture.isReady = true;
  6480. }, extensions);
  6481. }
  6482. return texture;
  6483. };
  6484. Engine.prototype._releaseTexture = function (texture) {
  6485. var gl = this._gl;
  6486. if (texture._framebuffer) {
  6487. gl.deleteFramebuffer(texture._framebuffer);
  6488. }
  6489. if (texture._depthBuffer) {
  6490. gl.deleteRenderbuffer(texture._depthBuffer);
  6491. }
  6492. gl.deleteTexture(texture);
  6493. // Unbind channels
  6494. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6495. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6497. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6498. this._activeTexturesCache[channel] = null;
  6499. }
  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.setTexture = function (channel, texture) {
  6523. if (channel < 0) {
  6524. return;
  6525. }
  6526. // Not ready?
  6527. if (!texture || !texture.isReady()) {
  6528. if (this._activeTexturesCache[channel] != null) {
  6529. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6530. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6531. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6532. this._activeTexturesCache[channel] = null;
  6533. }
  6534. return;
  6535. }
  6536. // Video
  6537. var alreadyActivated = false;
  6538. if (texture instanceof BABYLON.VideoTexture) {
  6539. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6540. alreadyActivated = true;
  6541. texture.update();
  6542. }
  6543. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6544. texture.delayLoad();
  6545. return;
  6546. }
  6547. if (this._activeTexturesCache[channel] === texture) {
  6548. return;
  6549. }
  6550. this._activeTexturesCache[channel] = texture;
  6551. var internalTexture = texture.getInternalTexture();
  6552. if (!alreadyActivated) {
  6553. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6554. }
  6555. if (internalTexture.isCube) {
  6556. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6557. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6558. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6559. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6560. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6561. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6562. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6563. }
  6564. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6565. }
  6566. else {
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6568. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6569. internalTexture._cachedWrapU = texture.wrapU;
  6570. switch (texture.wrapU) {
  6571. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6572. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6573. break;
  6574. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6575. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6576. break;
  6577. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6578. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6579. break;
  6580. }
  6581. }
  6582. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6583. internalTexture._cachedWrapV = texture.wrapV;
  6584. switch (texture.wrapV) {
  6585. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6587. break;
  6588. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6589. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6590. break;
  6591. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6592. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6593. break;
  6594. }
  6595. }
  6596. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6597. }
  6598. };
  6599. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6600. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6601. var value = texture.anisotropicFilteringLevel;
  6602. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6603. value = 1;
  6604. }
  6605. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6606. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6607. texture._cachedAnisotropicFilteringLevel = value;
  6608. }
  6609. };
  6610. Engine.prototype.readPixels = function (x, y, width, height) {
  6611. var data = new Uint8Array(height * width * 4);
  6612. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6613. return data;
  6614. };
  6615. Engine.prototype.releaseInternalTexture = function (texture) {
  6616. if (!texture) {
  6617. return;
  6618. }
  6619. texture.references--;
  6620. // Final reference ?
  6621. if (texture.references === 0) {
  6622. var texturesCache = this.getLoadedTexturesCache();
  6623. var index = texturesCache.indexOf(texture);
  6624. if (index > -1) {
  6625. texturesCache.splice(index, 1);
  6626. }
  6627. this._releaseTexture(texture);
  6628. }
  6629. };
  6630. // Dispose
  6631. Engine.prototype.dispose = function () {
  6632. this.hideLoadingUI();
  6633. this.stopRenderLoop();
  6634. // Release scenes
  6635. while (this.scenes.length) {
  6636. this.scenes[0].dispose();
  6637. }
  6638. // Release audio engine
  6639. Engine.audioEngine.dispose();
  6640. // Release effects
  6641. for (var name in this._compiledEffects) {
  6642. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6643. }
  6644. // Unbind
  6645. for (var i in this._vertexAttribArrays) {
  6646. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6647. continue;
  6648. }
  6649. this._gl.disableVertexAttribArray(i);
  6650. }
  6651. this._gl = null;
  6652. // Events
  6653. window.removeEventListener("blur", this._onBlur);
  6654. window.removeEventListener("focus", this._onFocus);
  6655. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6656. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6657. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6658. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6659. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6660. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6661. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6662. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6663. };
  6664. // Loading screen
  6665. Engine.prototype.displayLoadingUI = function () {
  6666. this._loadingScreen.displayLoadingUI();
  6667. };
  6668. Engine.prototype.hideLoadingUI = function () {
  6669. this._loadingScreen.hideLoadingUI();
  6670. };
  6671. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6672. get: function () {
  6673. return this._loadingScreen;
  6674. },
  6675. set: function (loadingScreen) {
  6676. this._loadingScreen = loadingScreen;
  6677. },
  6678. enumerable: true,
  6679. configurable: true
  6680. });
  6681. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6682. set: function (text) {
  6683. this._loadingScreen.loadingUIText = text;
  6684. },
  6685. enumerable: true,
  6686. configurable: true
  6687. });
  6688. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6689. set: function (color) {
  6690. this._loadingScreen.loadingUIBackgroundColor = color;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. // FPS
  6696. Engine.prototype.getFps = function () {
  6697. return this.fps;
  6698. };
  6699. Engine.prototype.getDeltaTime = function () {
  6700. return this.deltaTime;
  6701. };
  6702. Engine.prototype._measureFps = function () {
  6703. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6704. var length = this.previousFramesDuration.length;
  6705. if (length >= 2) {
  6706. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6707. }
  6708. if (length >= this.fpsRange) {
  6709. if (length > this.fpsRange) {
  6710. this.previousFramesDuration.splice(0, 1);
  6711. length = this.previousFramesDuration.length;
  6712. }
  6713. var sum = 0;
  6714. for (var id = 0; id < length - 1; id++) {
  6715. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6716. }
  6717. this.fps = 1000.0 / (sum / (length - 1));
  6718. }
  6719. };
  6720. // Statics
  6721. Engine.isSupported = function () {
  6722. try {
  6723. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6724. if (navigator.isCocoonJS) {
  6725. return true;
  6726. }
  6727. var tempcanvas = document.createElement("canvas");
  6728. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6729. return gl != null && !!window.WebGLRenderingContext;
  6730. }
  6731. catch (e) {
  6732. return false;
  6733. }
  6734. };
  6735. // Const statics
  6736. Engine._ALPHA_DISABLE = 0;
  6737. Engine._ALPHA_ADD = 1;
  6738. Engine._ALPHA_COMBINE = 2;
  6739. Engine._ALPHA_SUBTRACT = 3;
  6740. Engine._ALPHA_MULTIPLY = 4;
  6741. Engine._ALPHA_MAXIMIZED = 5;
  6742. Engine._ALPHA_ONEONE = 6;
  6743. Engine._DELAYLOADSTATE_NONE = 0;
  6744. Engine._DELAYLOADSTATE_LOADED = 1;
  6745. Engine._DELAYLOADSTATE_LOADING = 2;
  6746. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6747. Engine._TEXTUREFORMAT_ALPHA = 0;
  6748. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6749. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6750. Engine._TEXTUREFORMAT_RGB = 4;
  6751. Engine._TEXTUREFORMAT_RGBA = 5;
  6752. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6753. Engine._TEXTURETYPE_FLOAT = 1;
  6754. // Updatable statics so stick with vars here
  6755. Engine.Epsilon = 0.001;
  6756. Engine.CollisionsEpsilon = 0.001;
  6757. Engine.CodeRepository = "src/";
  6758. Engine.ShadersRepository = "src/Shaders/";
  6759. return Engine;
  6760. })();
  6761. BABYLON.Engine = Engine;
  6762. })(BABYLON || (BABYLON = {}));
  6763. var BABYLON;
  6764. (function (BABYLON) {
  6765. /**
  6766. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6767. */
  6768. var Node = (function () {
  6769. /**
  6770. * @constructor
  6771. * @param {string} name - the name and id to be given to this node
  6772. * @param {BABYLON.Scene} the scene this node will be added to
  6773. */
  6774. function Node(name, scene) {
  6775. this.state = "";
  6776. this.animations = new Array();
  6777. this._childrenFlag = -1;
  6778. this._isEnabled = true;
  6779. this._isReady = true;
  6780. this._currentRenderId = -1;
  6781. this._parentRenderId = -1;
  6782. this.name = name;
  6783. this.id = name;
  6784. this._scene = scene;
  6785. this._initCache();
  6786. }
  6787. Node.prototype.getScene = function () {
  6788. return this._scene;
  6789. };
  6790. Node.prototype.getEngine = function () {
  6791. return this._scene.getEngine();
  6792. };
  6793. // override it in derived class
  6794. Node.prototype.getWorldMatrix = function () {
  6795. return BABYLON.Matrix.Identity();
  6796. };
  6797. // override it in derived class if you add new variables to the cache
  6798. // and call the parent class method
  6799. Node.prototype._initCache = function () {
  6800. this._cache = {};
  6801. this._cache.parent = undefined;
  6802. };
  6803. Node.prototype.updateCache = function (force) {
  6804. if (!force && this.isSynchronized())
  6805. return;
  6806. this._cache.parent = this.parent;
  6807. this._updateCache();
  6808. };
  6809. // override it in derived class if you add new variables to the cache
  6810. // and call the parent class method if !ignoreParentClass
  6811. Node.prototype._updateCache = function (ignoreParentClass) {
  6812. };
  6813. // override it in derived class if you add new variables to the cache
  6814. Node.prototype._isSynchronized = function () {
  6815. return true;
  6816. };
  6817. Node.prototype._markSyncedWithParent = function () {
  6818. this._parentRenderId = this.parent._currentRenderId;
  6819. };
  6820. Node.prototype.isSynchronizedWithParent = function () {
  6821. if (!this.parent) {
  6822. return true;
  6823. }
  6824. if (this._parentRenderId !== this.parent._currentRenderId) {
  6825. return false;
  6826. }
  6827. return this.parent.isSynchronized();
  6828. };
  6829. Node.prototype.isSynchronized = function (updateCache) {
  6830. var check = this.hasNewParent();
  6831. check = check || !this.isSynchronizedWithParent();
  6832. check = check || !this._isSynchronized();
  6833. if (updateCache)
  6834. this.updateCache(true);
  6835. return !check;
  6836. };
  6837. Node.prototype.hasNewParent = function (update) {
  6838. if (this._cache.parent === this.parent)
  6839. return false;
  6840. if (update)
  6841. this._cache.parent = this.parent;
  6842. return true;
  6843. };
  6844. /**
  6845. * Is this node ready to be used/rendered
  6846. * @return {boolean} is it ready
  6847. */
  6848. Node.prototype.isReady = function () {
  6849. return this._isReady;
  6850. };
  6851. /**
  6852. * Is this node enabled.
  6853. * If the node has a parent and is enabled, the parent will be inspected as well.
  6854. * @return {boolean} whether this node (and its parent) is enabled.
  6855. * @see setEnabled
  6856. */
  6857. Node.prototype.isEnabled = function () {
  6858. if (!this._isEnabled) {
  6859. return false;
  6860. }
  6861. if (this.parent) {
  6862. return this.parent.isEnabled();
  6863. }
  6864. return true;
  6865. };
  6866. /**
  6867. * Set the enabled state of this node.
  6868. * @param {boolean} value - the new enabled state
  6869. * @see isEnabled
  6870. */
  6871. Node.prototype.setEnabled = function (value) {
  6872. this._isEnabled = value;
  6873. };
  6874. /**
  6875. * Is this node a descendant of the given node.
  6876. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6877. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6878. * @see parent
  6879. */
  6880. Node.prototype.isDescendantOf = function (ancestor) {
  6881. if (this.parent) {
  6882. if (this.parent === ancestor) {
  6883. return true;
  6884. }
  6885. return this.parent.isDescendantOf(ancestor);
  6886. }
  6887. return false;
  6888. };
  6889. Node.prototype._getDescendants = function (list, results) {
  6890. for (var index = 0; index < list.length; index++) {
  6891. var item = list[index];
  6892. if (item.isDescendantOf(this)) {
  6893. results.push(item);
  6894. }
  6895. }
  6896. };
  6897. /**
  6898. * Will return all nodes that have this node as parent.
  6899. * @return {BABYLON.Node[]} all children nodes of all types.
  6900. */
  6901. Node.prototype.getDescendants = function () {
  6902. var results = [];
  6903. this._getDescendants(this._scene.meshes, results);
  6904. this._getDescendants(this._scene.lights, results);
  6905. this._getDescendants(this._scene.cameras, results);
  6906. return results;
  6907. };
  6908. Node.prototype._setReady = function (state) {
  6909. if (state === this._isReady) {
  6910. return;
  6911. }
  6912. if (!state) {
  6913. this._isReady = false;
  6914. return;
  6915. }
  6916. this._isReady = true;
  6917. if (this.onReady) {
  6918. this.onReady(this);
  6919. }
  6920. };
  6921. Node.prototype.getAnimationByName = function (name) {
  6922. for (var i = 0; i < this.animations.length; i++) {
  6923. var animation = this.animations[i];
  6924. if (animation.name === name) {
  6925. return animation;
  6926. }
  6927. }
  6928. return null;
  6929. };
  6930. return Node;
  6931. })();
  6932. BABYLON.Node = Node;
  6933. })(BABYLON || (BABYLON = {}));
  6934. var BABYLON;
  6935. (function (BABYLON) {
  6936. var FilesInput = (function () {
  6937. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6938. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6939. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6940. this._engine = p_engine;
  6941. this._canvas = p_canvas;
  6942. this._currentScene = p_scene;
  6943. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6944. this._progressCallback = p_progressCallback;
  6945. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6946. this._textureLoadingCallback = p_textureLoadingCallback;
  6947. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6948. }
  6949. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6950. var _this = this;
  6951. if (p_elementToMonitor) {
  6952. this._elementToMonitor = p_elementToMonitor;
  6953. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6954. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6955. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6956. }
  6957. };
  6958. FilesInput.prototype.renderFunction = function () {
  6959. if (this._additionnalRenderLoopLogicCallback) {
  6960. this._additionnalRenderLoopLogicCallback();
  6961. }
  6962. if (this._currentScene) {
  6963. if (this._textureLoadingCallback) {
  6964. var remaining = this._currentScene.getWaitingItemsCount();
  6965. if (remaining > 0) {
  6966. this._textureLoadingCallback(remaining);
  6967. }
  6968. }
  6969. this._currentScene.render();
  6970. }
  6971. };
  6972. FilesInput.prototype.drag = function (e) {
  6973. e.stopPropagation();
  6974. e.preventDefault();
  6975. };
  6976. FilesInput.prototype.drop = function (eventDrop) {
  6977. eventDrop.stopPropagation();
  6978. eventDrop.preventDefault();
  6979. this.loadFiles(eventDrop);
  6980. };
  6981. FilesInput.prototype.loadFiles = function (event) {
  6982. if (this._startingProcessingFilesCallback)
  6983. this._startingProcessingFilesCallback();
  6984. // Handling data transfer via drag'n'drop
  6985. if (event && event.dataTransfer && event.dataTransfer.files) {
  6986. this._filesToLoad = event.dataTransfer.files;
  6987. }
  6988. // Handling files from input files
  6989. if (event && event.target && event.target.files) {
  6990. this._filesToLoad = event.target.files;
  6991. }
  6992. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6993. for (var i = 0; i < this._filesToLoad.length; i++) {
  6994. switch (this._filesToLoad[i].type) {
  6995. case "image/jpeg":
  6996. case "image/png":
  6997. case "image/bmp":
  6998. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6999. break;
  7000. case "image/targa":
  7001. case "image/vnd.ms-dds":
  7002. case "audio/wav":
  7003. case "audio/x-wav":
  7004. case "audio/mp3":
  7005. case "audio/mpeg":
  7006. case "audio/mpeg3":
  7007. case "audio/x-mpeg-3":
  7008. case "audio/ogg":
  7009. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7010. break;
  7011. default:
  7012. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7013. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7014. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7015. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7016. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7017. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7018. this._sceneFileToLoad = this._filesToLoad[i];
  7019. }
  7020. break;
  7021. }
  7022. }
  7023. this.reload();
  7024. }
  7025. };
  7026. FilesInput.prototype.reload = function () {
  7027. var _this = this;
  7028. var that = this;
  7029. // If a ".babylon" file has been provided
  7030. if (this._sceneFileToLoad) {
  7031. if (this._currentScene) {
  7032. if (BABYLON.Tools.errorsCount > 0) {
  7033. BABYLON.Tools.ClearLogCache();
  7034. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7035. }
  7036. this._engine.stopRenderLoop();
  7037. this._currentScene.dispose();
  7038. }
  7039. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7040. that._currentScene = newScene;
  7041. // Wait for textures and shaders to be ready
  7042. that._currentScene.executeWhenReady(function () {
  7043. // Attach camera to canvas inputs
  7044. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7045. that._currentScene.createDefaultCameraOrLight();
  7046. }
  7047. that._currentScene.activeCamera.attachControl(that._canvas);
  7048. if (that._sceneLoadedCallback) {
  7049. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7050. }
  7051. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7052. });
  7053. }, function (progress) {
  7054. if (_this._progressCallback) {
  7055. _this._progressCallback(progress);
  7056. }
  7057. });
  7058. }
  7059. else {
  7060. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7061. }
  7062. };
  7063. FilesInput.FilesTextures = new Array();
  7064. FilesInput.FilesToLoad = new Array();
  7065. return FilesInput;
  7066. })();
  7067. BABYLON.FilesInput = FilesInput;
  7068. })(BABYLON || (BABYLON = {}));
  7069. var BABYLON;
  7070. (function (BABYLON) {
  7071. var IntersectionInfo = (function () {
  7072. function IntersectionInfo(bu, bv, distance) {
  7073. this.bu = bu;
  7074. this.bv = bv;
  7075. this.distance = distance;
  7076. this.faceId = 0;
  7077. this.subMeshId = 0;
  7078. }
  7079. return IntersectionInfo;
  7080. })();
  7081. BABYLON.IntersectionInfo = IntersectionInfo;
  7082. var PickingInfo = (function () {
  7083. function PickingInfo() {
  7084. this.hit = false;
  7085. this.distance = 0;
  7086. this.pickedPoint = null;
  7087. this.pickedMesh = null;
  7088. this.bu = 0;
  7089. this.bv = 0;
  7090. this.faceId = -1;
  7091. this.subMeshId = 0;
  7092. this.pickedSprite = null;
  7093. }
  7094. // Methods
  7095. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7096. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7097. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7098. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7099. return null;
  7100. }
  7101. var indices = this.pickedMesh.getIndices();
  7102. var result;
  7103. if (useVerticesNormals) {
  7104. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7105. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7106. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7107. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7108. normal0 = normal0.scale(this.bu);
  7109. normal1 = normal1.scale(this.bv);
  7110. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7111. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7112. }
  7113. else {
  7114. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7115. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7116. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7117. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7118. var p1p2 = vertex1.subtract(vertex2);
  7119. var p3p2 = vertex3.subtract(vertex2);
  7120. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7121. }
  7122. if (useWorldCoordinates) {
  7123. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7124. }
  7125. return BABYLON.Vector3.Normalize(result);
  7126. };
  7127. PickingInfo.prototype.getTextureCoordinates = function () {
  7128. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7129. return null;
  7130. }
  7131. var indices = this.pickedMesh.getIndices();
  7132. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7133. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7134. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7135. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7136. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7137. uv1 = uv1.scale(this.bu);
  7138. uv2 = uv2.scale(this.bv);
  7139. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7140. };
  7141. return PickingInfo;
  7142. })();
  7143. BABYLON.PickingInfo = PickingInfo;
  7144. })(BABYLON || (BABYLON = {}));
  7145. var BABYLON;
  7146. (function (BABYLON) {
  7147. var BoundingSphere = (function () {
  7148. function BoundingSphere(minimum, maximum) {
  7149. this.minimum = minimum;
  7150. this.maximum = maximum;
  7151. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7152. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7153. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7154. this.radius = distance * 0.5;
  7155. this.centerWorld = BABYLON.Vector3.Zero();
  7156. this._update(BABYLON.Matrix.Identity());
  7157. }
  7158. // Methods
  7159. BoundingSphere.prototype._update = function (world) {
  7160. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7161. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7162. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7163. };
  7164. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7165. for (var i = 0; i < 6; i++) {
  7166. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7167. return false;
  7168. }
  7169. return true;
  7170. };
  7171. BoundingSphere.prototype.intersectsPoint = function (point) {
  7172. var x = this.centerWorld.x - point.x;
  7173. var y = this.centerWorld.y - point.y;
  7174. var z = this.centerWorld.z - point.z;
  7175. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7176. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7177. return false;
  7178. return true;
  7179. };
  7180. // Statics
  7181. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7182. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7183. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7184. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7185. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7186. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7187. return false;
  7188. return true;
  7189. };
  7190. return BoundingSphere;
  7191. })();
  7192. BABYLON.BoundingSphere = BoundingSphere;
  7193. })(BABYLON || (BABYLON = {}));
  7194. var BABYLON;
  7195. (function (BABYLON) {
  7196. var BoundingBox = (function () {
  7197. function BoundingBox(minimum, maximum) {
  7198. this.minimum = minimum;
  7199. this.maximum = maximum;
  7200. this.vectors = new Array();
  7201. this.vectorsWorld = new Array();
  7202. // Bounding vectors
  7203. this.vectors.push(this.minimum.clone());
  7204. this.vectors.push(this.maximum.clone());
  7205. this.vectors.push(this.minimum.clone());
  7206. this.vectors[2].x = this.maximum.x;
  7207. this.vectors.push(this.minimum.clone());
  7208. this.vectors[3].y = this.maximum.y;
  7209. this.vectors.push(this.minimum.clone());
  7210. this.vectors[4].z = this.maximum.z;
  7211. this.vectors.push(this.maximum.clone());
  7212. this.vectors[5].z = this.minimum.z;
  7213. this.vectors.push(this.maximum.clone());
  7214. this.vectors[6].x = this.minimum.x;
  7215. this.vectors.push(this.maximum.clone());
  7216. this.vectors[7].y = this.minimum.y;
  7217. // OBB
  7218. this.center = this.maximum.add(this.minimum).scale(0.5);
  7219. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7220. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7221. // World
  7222. for (var index = 0; index < this.vectors.length; index++) {
  7223. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7224. }
  7225. this.minimumWorld = BABYLON.Vector3.Zero();
  7226. this.maximumWorld = BABYLON.Vector3.Zero();
  7227. this._update(BABYLON.Matrix.Identity());
  7228. }
  7229. // Methods
  7230. BoundingBox.prototype.getWorldMatrix = function () {
  7231. return this._worldMatrix;
  7232. };
  7233. BoundingBox.prototype._update = function (world) {
  7234. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7235. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7236. for (var index = 0; index < this.vectors.length; index++) {
  7237. var v = this.vectorsWorld[index];
  7238. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7239. if (v.x < this.minimumWorld.x)
  7240. this.minimumWorld.x = v.x;
  7241. if (v.y < this.minimumWorld.y)
  7242. this.minimumWorld.y = v.y;
  7243. if (v.z < this.minimumWorld.z)
  7244. this.minimumWorld.z = v.z;
  7245. if (v.x > this.maximumWorld.x)
  7246. this.maximumWorld.x = v.x;
  7247. if (v.y > this.maximumWorld.y)
  7248. this.maximumWorld.y = v.y;
  7249. if (v.z > this.maximumWorld.z)
  7250. this.maximumWorld.z = v.z;
  7251. }
  7252. // OBB
  7253. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7254. this.center.scaleInPlace(0.5);
  7255. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7256. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7257. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7258. this._worldMatrix = world;
  7259. };
  7260. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7261. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7262. };
  7263. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7264. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7265. };
  7266. BoundingBox.prototype.intersectsPoint = function (point) {
  7267. var delta = -BABYLON.Engine.Epsilon;
  7268. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7269. return false;
  7270. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7271. return false;
  7272. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7273. return false;
  7274. return true;
  7275. };
  7276. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7277. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7278. };
  7279. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7280. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7281. return false;
  7282. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7283. return false;
  7284. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7285. return false;
  7286. return true;
  7287. };
  7288. // Statics
  7289. BoundingBox.Intersects = function (box0, box1) {
  7290. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7291. return false;
  7292. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7293. return false;
  7294. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7295. return false;
  7296. return true;
  7297. };
  7298. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7299. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7300. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7301. return (num <= (sphereRadius * sphereRadius));
  7302. };
  7303. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7304. for (var p = 0; p < 6; p++) {
  7305. for (var i = 0; i < 8; i++) {
  7306. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7307. return false;
  7308. }
  7309. }
  7310. }
  7311. return true;
  7312. };
  7313. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7314. for (var p = 0; p < 6; p++) {
  7315. var inCount = 8;
  7316. for (var i = 0; i < 8; i++) {
  7317. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7318. --inCount;
  7319. }
  7320. else {
  7321. break;
  7322. }
  7323. }
  7324. if (inCount === 0)
  7325. return false;
  7326. }
  7327. return true;
  7328. };
  7329. return BoundingBox;
  7330. })();
  7331. BABYLON.BoundingBox = BoundingBox;
  7332. })(BABYLON || (BABYLON = {}));
  7333. var BABYLON;
  7334. (function (BABYLON) {
  7335. var computeBoxExtents = function (axis, box) {
  7336. var p = BABYLON.Vector3.Dot(box.center, axis);
  7337. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7338. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7339. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7340. var r = r0 + r1 + r2;
  7341. return {
  7342. min: p - r,
  7343. max: p + r
  7344. };
  7345. };
  7346. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7347. var axisOverlap = function (axis, box0, box1) {
  7348. var result0 = computeBoxExtents(axis, box0);
  7349. var result1 = computeBoxExtents(axis, box1);
  7350. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7351. };
  7352. var BoundingInfo = (function () {
  7353. function BoundingInfo(minimum, maximum) {
  7354. this.minimum = minimum;
  7355. this.maximum = maximum;
  7356. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7357. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7358. }
  7359. // Methods
  7360. BoundingInfo.prototype._update = function (world) {
  7361. this.boundingBox._update(world);
  7362. this.boundingSphere._update(world);
  7363. };
  7364. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7365. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7366. return false;
  7367. return this.boundingBox.isInFrustum(frustumPlanes);
  7368. };
  7369. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7370. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7371. };
  7372. BoundingInfo.prototype._checkCollision = function (collider) {
  7373. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7374. };
  7375. BoundingInfo.prototype.intersectsPoint = function (point) {
  7376. if (!this.boundingSphere.centerWorld) {
  7377. return false;
  7378. }
  7379. if (!this.boundingSphere.intersectsPoint(point)) {
  7380. return false;
  7381. }
  7382. if (!this.boundingBox.intersectsPoint(point)) {
  7383. return false;
  7384. }
  7385. return true;
  7386. };
  7387. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7388. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7389. return false;
  7390. }
  7391. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7392. return false;
  7393. }
  7394. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7395. return false;
  7396. }
  7397. if (!precise) {
  7398. return true;
  7399. }
  7400. var box0 = this.boundingBox;
  7401. var box1 = boundingInfo.boundingBox;
  7402. if (!axisOverlap(box0.directions[0], box0, box1))
  7403. return false;
  7404. if (!axisOverlap(box0.directions[1], box0, box1))
  7405. return false;
  7406. if (!axisOverlap(box0.directions[2], box0, box1))
  7407. return false;
  7408. if (!axisOverlap(box1.directions[0], box0, box1))
  7409. return false;
  7410. if (!axisOverlap(box1.directions[1], box0, box1))
  7411. return false;
  7412. if (!axisOverlap(box1.directions[2], box0, box1))
  7413. return false;
  7414. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7415. return false;
  7416. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7417. return false;
  7418. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7419. return false;
  7420. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7421. return false;
  7422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7423. return false;
  7424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7425. return false;
  7426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7427. return false;
  7428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7429. return false;
  7430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7431. return false;
  7432. return true;
  7433. };
  7434. return BoundingInfo;
  7435. })();
  7436. BABYLON.BoundingInfo = BoundingInfo;
  7437. })(BABYLON || (BABYLON = {}));
  7438. var BABYLON;
  7439. (function (BABYLON) {
  7440. var AbstractMesh = (function (_super) {
  7441. __extends(AbstractMesh, _super);
  7442. function AbstractMesh(name, scene) {
  7443. var _this = this;
  7444. _super.call(this, name, scene);
  7445. // Properties
  7446. this.definedFacingForward = true; // orientation for POV movement & rotation
  7447. this.position = new BABYLON.Vector3(0, 0, 0);
  7448. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7449. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7450. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7451. this.visibility = 1.0;
  7452. this.alphaIndex = Number.MAX_VALUE;
  7453. this.infiniteDistance = false;
  7454. this.isVisible = true;
  7455. this.isPickable = true;
  7456. this.showBoundingBox = false;
  7457. this.showSubMeshesBoundingBox = false;
  7458. this.onDispose = null;
  7459. this.isBlocker = false;
  7460. this.renderingGroupId = 0;
  7461. this.receiveShadows = false;
  7462. this.renderOutline = false;
  7463. this.outlineColor = BABYLON.Color3.Red();
  7464. this.outlineWidth = 0.02;
  7465. this.renderOverlay = false;
  7466. this.overlayColor = BABYLON.Color3.Red();
  7467. this.overlayAlpha = 0.5;
  7468. this.hasVertexAlpha = false;
  7469. this.useVertexColors = true;
  7470. this.applyFog = true;
  7471. this.computeBonesUsingShaders = true;
  7472. this.scalingDeterminant = 1;
  7473. this.numBoneInfluencers = 4;
  7474. this.useOctreeForRenderingSelection = true;
  7475. this.useOctreeForPicking = true;
  7476. this.useOctreeForCollisions = true;
  7477. this.layerMask = 0x0FFFFFFF;
  7478. this.alwaysSelectAsActiveMesh = false;
  7479. // Physics
  7480. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7481. // Collisions
  7482. this._checkCollisions = false;
  7483. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7484. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7485. this._collider = new BABYLON.Collider();
  7486. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7487. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7488. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7489. // Edges
  7490. this.edgesWidth = 1;
  7491. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7492. // Cache
  7493. this._localScaling = BABYLON.Matrix.Zero();
  7494. this._localRotation = BABYLON.Matrix.Zero();
  7495. this._localTranslation = BABYLON.Matrix.Zero();
  7496. this._localBillboard = BABYLON.Matrix.Zero();
  7497. this._localPivotScaling = BABYLON.Matrix.Zero();
  7498. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7499. this._localWorld = BABYLON.Matrix.Zero();
  7500. this._worldMatrix = BABYLON.Matrix.Zero();
  7501. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7502. this._absolutePosition = BABYLON.Vector3.Zero();
  7503. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7504. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7505. this._isDirty = false;
  7506. this._pivotMatrix = BABYLON.Matrix.Identity();
  7507. this._isDisposed = false;
  7508. this._renderId = 0;
  7509. this._intersectionsInProgress = new Array();
  7510. this._onAfterWorldMatrixUpdate = new Array();
  7511. this._isWorldMatrixFrozen = false;
  7512. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7513. if (collidedMesh === void 0) { collidedMesh = null; }
  7514. //TODO move this to the collision coordinator!
  7515. if (_this.getScene().workerCollisions)
  7516. newPosition.multiplyInPlace(_this._collider.radius);
  7517. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7518. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7519. _this.position.addInPlace(_this._diffPositionForCollisions);
  7520. }
  7521. if (_this.onCollide && collidedMesh) {
  7522. _this.onCollide(collidedMesh);
  7523. }
  7524. };
  7525. scene.addMesh(this);
  7526. }
  7527. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7528. get: function () {
  7529. return AbstractMesh._BILLBOARDMODE_NONE;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7535. get: function () {
  7536. return AbstractMesh._BILLBOARDMODE_X;
  7537. },
  7538. enumerable: true,
  7539. configurable: true
  7540. });
  7541. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7542. get: function () {
  7543. return AbstractMesh._BILLBOARDMODE_Y;
  7544. },
  7545. enumerable: true,
  7546. configurable: true
  7547. });
  7548. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7549. get: function () {
  7550. return AbstractMesh._BILLBOARDMODE_Z;
  7551. },
  7552. enumerable: true,
  7553. configurable: true
  7554. });
  7555. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7556. get: function () {
  7557. return AbstractMesh._BILLBOARDMODE_ALL;
  7558. },
  7559. enumerable: true,
  7560. configurable: true
  7561. });
  7562. // Methods
  7563. AbstractMesh.prototype.disableEdgesRendering = function () {
  7564. if (this._edgesRenderer !== undefined) {
  7565. this._edgesRenderer.dispose();
  7566. this._edgesRenderer = undefined;
  7567. }
  7568. };
  7569. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7570. if (epsilon === void 0) { epsilon = 0.95; }
  7571. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7572. this.disableEdgesRendering();
  7573. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7574. };
  7575. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7576. get: function () {
  7577. return false;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. AbstractMesh.prototype.getLOD = function (camera) {
  7583. return this;
  7584. };
  7585. AbstractMesh.prototype.getTotalVertices = function () {
  7586. return 0;
  7587. };
  7588. AbstractMesh.prototype.getIndices = function () {
  7589. return null;
  7590. };
  7591. AbstractMesh.prototype.getVerticesData = function (kind) {
  7592. return null;
  7593. };
  7594. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7595. return false;
  7596. };
  7597. AbstractMesh.prototype.getBoundingInfo = function () {
  7598. if (this._masterMesh) {
  7599. return this._masterMesh.getBoundingInfo();
  7600. }
  7601. if (!this._boundingInfo) {
  7602. this._updateBoundingInfo();
  7603. }
  7604. return this._boundingInfo;
  7605. };
  7606. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7607. get: function () {
  7608. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7609. },
  7610. enumerable: true,
  7611. configurable: true
  7612. });
  7613. AbstractMesh.prototype._preActivate = function () {
  7614. };
  7615. AbstractMesh.prototype._activate = function (renderId) {
  7616. this._renderId = renderId;
  7617. };
  7618. AbstractMesh.prototype.getWorldMatrix = function () {
  7619. if (this._masterMesh) {
  7620. return this._masterMesh.getWorldMatrix();
  7621. }
  7622. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7623. this.computeWorldMatrix();
  7624. }
  7625. return this._worldMatrix;
  7626. };
  7627. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7628. get: function () {
  7629. return this._worldMatrix;
  7630. },
  7631. enumerable: true,
  7632. configurable: true
  7633. });
  7634. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7635. get: function () {
  7636. return this._absolutePosition;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7642. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7643. this.computeWorldMatrix(true);
  7644. this._isWorldMatrixFrozen = true;
  7645. };
  7646. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7647. this._isWorldMatrixFrozen = false;
  7648. this.computeWorldMatrix(true);
  7649. };
  7650. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7651. get: function () {
  7652. return this._isWorldMatrixFrozen;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7658. axis.normalize();
  7659. if (!this.rotationQuaternion) {
  7660. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7661. this.rotation = BABYLON.Vector3.Zero();
  7662. }
  7663. var rotationQuaternion;
  7664. if (!space || space === BABYLON.Space.LOCAL) {
  7665. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7666. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7667. }
  7668. else {
  7669. if (this.parent) {
  7670. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7671. invertParentWorldMatrix.invert();
  7672. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7673. }
  7674. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7675. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7676. }
  7677. };
  7678. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7679. var displacementVector = axis.scale(distance);
  7680. if (!space || space === BABYLON.Space.LOCAL) {
  7681. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7682. this.setPositionWithLocalVector(tempV3);
  7683. }
  7684. else {
  7685. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7686. }
  7687. };
  7688. AbstractMesh.prototype.getAbsolutePosition = function () {
  7689. this.computeWorldMatrix();
  7690. return this._absolutePosition;
  7691. };
  7692. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7693. if (!absolutePosition) {
  7694. return;
  7695. }
  7696. var absolutePositionX;
  7697. var absolutePositionY;
  7698. var absolutePositionZ;
  7699. if (absolutePosition.x === undefined) {
  7700. if (arguments.length < 3) {
  7701. return;
  7702. }
  7703. absolutePositionX = arguments[0];
  7704. absolutePositionY = arguments[1];
  7705. absolutePositionZ = arguments[2];
  7706. }
  7707. else {
  7708. absolutePositionX = absolutePosition.x;
  7709. absolutePositionY = absolutePosition.y;
  7710. absolutePositionZ = absolutePosition.z;
  7711. }
  7712. if (this.parent) {
  7713. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7714. invertParentWorldMatrix.invert();
  7715. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7716. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7717. }
  7718. else {
  7719. this.position.x = absolutePositionX;
  7720. this.position.y = absolutePositionY;
  7721. this.position.z = absolutePositionZ;
  7722. }
  7723. };
  7724. // ================================== Point of View Movement =================================
  7725. /**
  7726. * Perform relative position change from the point of view of behind the front of the mesh.
  7727. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7728. * Supports definition of mesh facing forward or backward.
  7729. * @param {number} amountRight
  7730. * @param {number} amountUp
  7731. * @param {number} amountForward
  7732. */
  7733. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7734. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7735. };
  7736. /**
  7737. * Calculate 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.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7745. var rotMatrix = new BABYLON.Matrix();
  7746. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7747. rotQuaternion.toRotationMatrix(rotMatrix);
  7748. var translationDelta = BABYLON.Vector3.Zero();
  7749. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7750. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7751. return translationDelta;
  7752. };
  7753. // ================================== Point of View Rotation =================================
  7754. /**
  7755. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7756. * Supports definition of mesh facing forward or backward.
  7757. * @param {number} flipBack
  7758. * @param {number} twirlClockwise
  7759. * @param {number} tiltRight
  7760. */
  7761. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7762. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7763. };
  7764. /**
  7765. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7766. * Supports definition of mesh facing forward or backward.
  7767. * @param {number} flipBack
  7768. * @param {number} twirlClockwise
  7769. * @param {number} tiltRight
  7770. */
  7771. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7772. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7773. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7774. };
  7775. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7776. this._pivotMatrix = matrix;
  7777. this._cache.pivotMatrixUpdated = true;
  7778. };
  7779. AbstractMesh.prototype.getPivotMatrix = function () {
  7780. return this._pivotMatrix;
  7781. };
  7782. AbstractMesh.prototype._isSynchronized = function () {
  7783. if (this._isDirty) {
  7784. return false;
  7785. }
  7786. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7787. return false;
  7788. if (this._cache.pivotMatrixUpdated) {
  7789. return false;
  7790. }
  7791. if (this.infiniteDistance) {
  7792. return false;
  7793. }
  7794. if (!this._cache.position.equals(this.position))
  7795. return false;
  7796. if (this.rotationQuaternion) {
  7797. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7798. return false;
  7799. }
  7800. else {
  7801. if (!this._cache.rotation.equals(this.rotation))
  7802. return false;
  7803. }
  7804. if (!this._cache.scaling.equals(this.scaling))
  7805. return false;
  7806. return true;
  7807. };
  7808. AbstractMesh.prototype._initCache = function () {
  7809. _super.prototype._initCache.call(this);
  7810. this._cache.localMatrixUpdated = false;
  7811. this._cache.position = BABYLON.Vector3.Zero();
  7812. this._cache.scaling = BABYLON.Vector3.Zero();
  7813. this._cache.rotation = BABYLON.Vector3.Zero();
  7814. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7815. };
  7816. AbstractMesh.prototype.markAsDirty = function (property) {
  7817. if (property === "rotation") {
  7818. this.rotationQuaternion = null;
  7819. }
  7820. this._currentRenderId = Number.MAX_VALUE;
  7821. this._isDirty = true;
  7822. };
  7823. AbstractMesh.prototype._updateBoundingInfo = function () {
  7824. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7825. this._boundingInfo._update(this.worldMatrixFromCache);
  7826. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7827. };
  7828. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7829. if (!this.subMeshes) {
  7830. return;
  7831. }
  7832. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7833. var subMesh = this.subMeshes[subIndex];
  7834. subMesh.updateBoundingInfo(matrix);
  7835. }
  7836. };
  7837. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7838. if (this._isWorldMatrixFrozen) {
  7839. return this._worldMatrix;
  7840. }
  7841. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7842. return this._worldMatrix;
  7843. }
  7844. this._cache.position.copyFrom(this.position);
  7845. this._cache.scaling.copyFrom(this.scaling);
  7846. this._cache.pivotMatrixUpdated = false;
  7847. this._currentRenderId = this.getScene().getRenderId();
  7848. this._isDirty = false;
  7849. // Scaling
  7850. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7851. // Rotation
  7852. if (this.rotationQuaternion) {
  7853. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7854. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7855. }
  7856. else {
  7857. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7858. this._cache.rotation.copyFrom(this.rotation);
  7859. }
  7860. // Translation
  7861. if (this.infiniteDistance && !this.parent) {
  7862. var camera = this.getScene().activeCamera;
  7863. if (camera) {
  7864. var cameraWorldMatrix = camera.getWorldMatrix();
  7865. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7866. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7867. }
  7868. }
  7869. else {
  7870. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7871. }
  7872. // Composing transformations
  7873. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7874. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7875. // Billboarding
  7876. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7877. var localPosition = this.position.clone();
  7878. var zero = this.getScene().activeCamera.globalPosition.clone();
  7879. if (this.parent && this.parent.position) {
  7880. localPosition.addInPlace(this.parent.position);
  7881. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7882. }
  7883. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7884. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7885. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7886. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7887. zero.y = localPosition.y + 0.001;
  7888. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7889. zero.z = localPosition.z + 0.001;
  7890. }
  7891. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7892. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7893. this._localBillboard.invert();
  7894. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7895. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7896. }
  7897. // Local world
  7898. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7899. // Parent
  7900. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7901. this._markSyncedWithParent();
  7902. if (this._meshToBoneReferal) {
  7903. if (!this._localMeshReferalTransform) {
  7904. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7905. }
  7906. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7907. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7908. }
  7909. else {
  7910. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7911. }
  7912. }
  7913. else {
  7914. this._worldMatrix.copyFrom(this._localWorld);
  7915. }
  7916. // Bounding info
  7917. this._updateBoundingInfo();
  7918. // Absolute position
  7919. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7920. // Callbacks
  7921. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7922. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7923. }
  7924. return this._worldMatrix;
  7925. };
  7926. /**
  7927. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7928. * @param func: callback function to add
  7929. */
  7930. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7931. this._onAfterWorldMatrixUpdate.push(func);
  7932. };
  7933. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7934. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7935. if (index > -1) {
  7936. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7937. }
  7938. };
  7939. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7940. this.computeWorldMatrix();
  7941. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7942. };
  7943. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7944. this.computeWorldMatrix();
  7945. var invLocalWorldMatrix = this._localWorld.clone();
  7946. invLocalWorldMatrix.invert();
  7947. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7948. };
  7949. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7950. this.computeWorldMatrix(true);
  7951. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7952. };
  7953. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7954. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7955. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7956. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7957. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7958. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7959. /// <returns>Mesh oriented towards targetMesh</returns>
  7960. yawCor = yawCor || 0; // default to zero if undefined
  7961. pitchCor = pitchCor || 0;
  7962. rollCor = rollCor || 0;
  7963. var dv = targetPoint.subtract(this.position);
  7964. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7965. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7966. var pitch = Math.atan2(dv.y, len);
  7967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7968. };
  7969. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7970. this._meshToBoneReferal = affectedMesh;
  7971. this.parent = bone;
  7972. if (bone.getWorldMatrix().determinant() < 0) {
  7973. this.scalingDeterminant *= -1;
  7974. }
  7975. };
  7976. AbstractMesh.prototype.detachFromBone = function () {
  7977. if (this.parent.getWorldMatrix().determinant() < 0) {
  7978. this.scalingDeterminant *= -1;
  7979. }
  7980. this._meshToBoneReferal = null;
  7981. this.parent = null;
  7982. };
  7983. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7984. return this._boundingInfo.isInFrustum(frustumPlanes);
  7985. };
  7986. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7987. if (!camera) {
  7988. camera = this.getScene().activeCamera;
  7989. }
  7990. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7991. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7992. return false;
  7993. }
  7994. return true;
  7995. };
  7996. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7997. if (!this._boundingInfo || !mesh._boundingInfo) {
  7998. return false;
  7999. }
  8000. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8001. };
  8002. AbstractMesh.prototype.intersectsPoint = function (point) {
  8003. if (!this._boundingInfo) {
  8004. return false;
  8005. }
  8006. return this._boundingInfo.intersectsPoint(point);
  8007. };
  8008. // Physics
  8009. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8010. var physicsEngine = this.getScene().getPhysicsEngine();
  8011. if (!physicsEngine) {
  8012. return null;
  8013. }
  8014. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8015. if (impostor.impostor) {
  8016. // Old API
  8017. options = impostor;
  8018. impostor = impostor.impostor;
  8019. }
  8020. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8021. physicsEngine._unregisterMesh(this);
  8022. return null;
  8023. }
  8024. if (!options) {
  8025. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8026. }
  8027. else {
  8028. if (!options.mass && options.mass !== 0)
  8029. options.mass = 0;
  8030. if (!options.friction && options.friction !== 0)
  8031. options.friction = 0.2;
  8032. if (!options.restitution && options.restitution !== 0)
  8033. options.restitution = 0.2;
  8034. }
  8035. this._physicImpostor = impostor;
  8036. this._physicsMass = options.mass;
  8037. this._physicsFriction = options.friction;
  8038. this._physicRestitution = options.restitution;
  8039. return physicsEngine._registerMesh(this, impostor, options);
  8040. };
  8041. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8042. if (!this._physicImpostor) {
  8043. return BABYLON.PhysicsEngine.NoImpostor;
  8044. }
  8045. return this._physicImpostor;
  8046. };
  8047. AbstractMesh.prototype.getPhysicsMass = function () {
  8048. if (!this._physicsMass) {
  8049. return 0;
  8050. }
  8051. return this._physicsMass;
  8052. };
  8053. AbstractMesh.prototype.getPhysicsFriction = function () {
  8054. if (!this._physicsFriction) {
  8055. return 0;
  8056. }
  8057. return this._physicsFriction;
  8058. };
  8059. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8060. if (!this._physicRestitution) {
  8061. return 0;
  8062. }
  8063. return this._physicRestitution;
  8064. };
  8065. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8066. if (!camera) {
  8067. camera = this.getScene().activeCamera;
  8068. }
  8069. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8070. };
  8071. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8072. if (!camera) {
  8073. camera = this.getScene().activeCamera;
  8074. }
  8075. return this.absolutePosition.subtract(camera.position).length();
  8076. };
  8077. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8078. if (!this._physicImpostor) {
  8079. return;
  8080. }
  8081. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8082. };
  8083. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8084. if (!this._physicImpostor) {
  8085. return;
  8086. }
  8087. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8088. };
  8089. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8090. if (!this._physicImpostor) {
  8091. return;
  8092. }
  8093. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8094. };
  8095. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8096. // Collisions
  8097. get: function () {
  8098. return this._checkCollisions;
  8099. },
  8100. set: function (collisionEnabled) {
  8101. this._checkCollisions = collisionEnabled;
  8102. if (this.getScene().workerCollisions) {
  8103. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8104. }
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8110. var globalPosition = this.getAbsolutePosition();
  8111. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8112. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8113. this._collider.radius = this.ellipsoid;
  8114. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8115. };
  8116. // Submeshes octree
  8117. /**
  8118. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8119. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8120. */
  8121. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8122. if (maxCapacity === void 0) { maxCapacity = 64; }
  8123. if (maxDepth === void 0) { maxDepth = 2; }
  8124. if (!this._submeshesOctree) {
  8125. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8126. }
  8127. this.computeWorldMatrix(true);
  8128. // Update octree
  8129. var bbox = this.getBoundingInfo().boundingBox;
  8130. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8131. return this._submeshesOctree;
  8132. };
  8133. // Collisions
  8134. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8135. this._generatePointsArray();
  8136. // Transformation
  8137. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8138. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8139. subMesh._lastColliderWorldVertices = [];
  8140. subMesh._trianglePlanes = [];
  8141. var start = subMesh.verticesStart;
  8142. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8143. for (var i = start; i < end; i++) {
  8144. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8145. }
  8146. }
  8147. // Collide
  8148. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8149. if (collider.collisionFound) {
  8150. collider.collidedMesh = this;
  8151. }
  8152. };
  8153. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8154. var subMeshes;
  8155. var len;
  8156. // Octrees
  8157. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8158. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8159. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8160. len = intersections.length;
  8161. subMeshes = intersections.data;
  8162. }
  8163. else {
  8164. subMeshes = this.subMeshes;
  8165. len = subMeshes.length;
  8166. }
  8167. for (var index = 0; index < len; index++) {
  8168. var subMesh = subMeshes[index];
  8169. // Bounding test
  8170. if (len > 1 && !subMesh._checkCollision(collider))
  8171. continue;
  8172. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8173. }
  8174. };
  8175. AbstractMesh.prototype._checkCollision = function (collider) {
  8176. // Bounding box test
  8177. if (!this._boundingInfo._checkCollision(collider))
  8178. return;
  8179. // Transformation matrix
  8180. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8181. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8182. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8183. };
  8184. // Picking
  8185. AbstractMesh.prototype._generatePointsArray = function () {
  8186. return false;
  8187. };
  8188. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8189. var pickingInfo = new BABYLON.PickingInfo();
  8190. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8191. return pickingInfo;
  8192. }
  8193. if (!this._generatePointsArray()) {
  8194. return pickingInfo;
  8195. }
  8196. var intersectInfo = null;
  8197. // Octrees
  8198. var subMeshes;
  8199. var len;
  8200. if (this._submeshesOctree && this.useOctreeForPicking) {
  8201. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8202. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8203. len = intersections.length;
  8204. subMeshes = intersections.data;
  8205. }
  8206. else {
  8207. subMeshes = this.subMeshes;
  8208. len = subMeshes.length;
  8209. }
  8210. for (var index = 0; index < len; index++) {
  8211. var subMesh = subMeshes[index];
  8212. // Bounding test
  8213. if (len > 1 && !subMesh.canIntersects(ray))
  8214. continue;
  8215. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8216. if (currentIntersectInfo) {
  8217. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8218. intersectInfo = currentIntersectInfo;
  8219. intersectInfo.subMeshId = index;
  8220. if (fastCheck) {
  8221. break;
  8222. }
  8223. }
  8224. }
  8225. }
  8226. if (intersectInfo) {
  8227. // Get picked point
  8228. var world = this.getWorldMatrix();
  8229. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8230. var direction = ray.direction.clone();
  8231. direction = direction.scale(intersectInfo.distance);
  8232. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8233. var pickedPoint = worldOrigin.add(worldDirection);
  8234. // Return result
  8235. pickingInfo.hit = true;
  8236. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8237. pickingInfo.pickedPoint = pickedPoint;
  8238. pickingInfo.pickedMesh = this;
  8239. pickingInfo.bu = intersectInfo.bu;
  8240. pickingInfo.bv = intersectInfo.bv;
  8241. pickingInfo.faceId = intersectInfo.faceId;
  8242. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8243. return pickingInfo;
  8244. }
  8245. return pickingInfo;
  8246. };
  8247. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8248. return null;
  8249. };
  8250. AbstractMesh.prototype.releaseSubMeshes = function () {
  8251. if (this.subMeshes) {
  8252. while (this.subMeshes.length) {
  8253. this.subMeshes[0].dispose();
  8254. }
  8255. }
  8256. else {
  8257. this.subMeshes = new Array();
  8258. }
  8259. };
  8260. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8261. var index;
  8262. // Animations
  8263. this.getScene().stopAnimation(this);
  8264. // Physics
  8265. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8266. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8267. }
  8268. // Intersections in progress
  8269. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8270. var other = this._intersectionsInProgress[index];
  8271. var pos = other._intersectionsInProgress.indexOf(this);
  8272. other._intersectionsInProgress.splice(pos, 1);
  8273. }
  8274. this._intersectionsInProgress = [];
  8275. // Edges
  8276. if (this._edgesRenderer) {
  8277. this._edgesRenderer.dispose();
  8278. this._edgesRenderer = null;
  8279. }
  8280. // SubMeshes
  8281. this.releaseSubMeshes();
  8282. // Remove from scene
  8283. this.getScene().removeMesh(this);
  8284. if (!doNotRecurse) {
  8285. // Particles
  8286. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8287. if (this.getScene().particleSystems[index].emitter === this) {
  8288. this.getScene().particleSystems[index].dispose();
  8289. index--;
  8290. }
  8291. }
  8292. // Children
  8293. var objects = this.getScene().meshes.slice(0);
  8294. for (index = 0; index < objects.length; index++) {
  8295. if (objects[index].parent === this) {
  8296. objects[index].dispose();
  8297. }
  8298. }
  8299. }
  8300. else {
  8301. for (index = 0; index < this.getScene().meshes.length; index++) {
  8302. var obj = this.getScene().meshes[index];
  8303. if (obj.parent === this) {
  8304. obj.parent = null;
  8305. obj.computeWorldMatrix(true);
  8306. }
  8307. }
  8308. }
  8309. this._onAfterWorldMatrixUpdate = [];
  8310. this._isDisposed = true;
  8311. // Callback
  8312. if (this.onDispose) {
  8313. this.onDispose();
  8314. }
  8315. };
  8316. // Statics
  8317. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8318. AbstractMesh._BILLBOARDMODE_X = 1;
  8319. AbstractMesh._BILLBOARDMODE_Y = 2;
  8320. AbstractMesh._BILLBOARDMODE_Z = 4;
  8321. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8322. return AbstractMesh;
  8323. })(BABYLON.Node);
  8324. BABYLON.AbstractMesh = AbstractMesh;
  8325. })(BABYLON || (BABYLON = {}));
  8326. var BABYLON;
  8327. (function (BABYLON) {
  8328. var Light = (function (_super) {
  8329. __extends(Light, _super);
  8330. function Light(name, scene) {
  8331. _super.call(this, name, scene);
  8332. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8333. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8334. this.intensity = 1.0;
  8335. this.range = Number.MAX_VALUE;
  8336. this.includeOnlyWithLayerMask = 0;
  8337. this.includedOnlyMeshes = new Array();
  8338. this.excludedMeshes = new Array();
  8339. this.excludeWithLayerMask = 0;
  8340. this._excludedMeshesIds = new Array();
  8341. this._includedOnlyMeshesIds = new Array();
  8342. scene.addLight(this);
  8343. }
  8344. Light.prototype.getShadowGenerator = function () {
  8345. return this._shadowGenerator;
  8346. };
  8347. Light.prototype.getAbsolutePosition = function () {
  8348. return BABYLON.Vector3.Zero();
  8349. };
  8350. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8351. };
  8352. Light.prototype._getWorldMatrix = function () {
  8353. return BABYLON.Matrix.Identity();
  8354. };
  8355. Light.prototype.canAffectMesh = function (mesh) {
  8356. if (!mesh) {
  8357. return true;
  8358. }
  8359. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8360. return false;
  8361. }
  8362. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8363. return false;
  8364. }
  8365. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8366. return false;
  8367. }
  8368. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8369. return false;
  8370. }
  8371. return true;
  8372. };
  8373. Light.prototype.getWorldMatrix = function () {
  8374. this._currentRenderId = this.getScene().getRenderId();
  8375. var worldMatrix = this._getWorldMatrix();
  8376. if (this.parent && this.parent.getWorldMatrix) {
  8377. if (!this._parentedWorldMatrix) {
  8378. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8379. }
  8380. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8381. this._markSyncedWithParent();
  8382. return this._parentedWorldMatrix;
  8383. }
  8384. return worldMatrix;
  8385. };
  8386. Light.prototype.dispose = function () {
  8387. if (this._shadowGenerator) {
  8388. this._shadowGenerator.dispose();
  8389. this._shadowGenerator = null;
  8390. }
  8391. // Animations
  8392. this.getScene().stopAnimation(this);
  8393. // Remove from scene
  8394. this.getScene().removeLight(this);
  8395. };
  8396. return Light;
  8397. })(BABYLON.Node);
  8398. BABYLON.Light = Light;
  8399. })(BABYLON || (BABYLON = {}));
  8400. var BABYLON;
  8401. (function (BABYLON) {
  8402. var PointLight = (function (_super) {
  8403. __extends(PointLight, _super);
  8404. function PointLight(name, position, scene) {
  8405. _super.call(this, name, scene);
  8406. this.position = position;
  8407. }
  8408. PointLight.prototype.getAbsolutePosition = function () {
  8409. return this.transformedPosition ? this.transformedPosition : this.position;
  8410. };
  8411. PointLight.prototype.computeTransformedPosition = function () {
  8412. if (this.parent && this.parent.getWorldMatrix) {
  8413. if (!this.transformedPosition) {
  8414. this.transformedPosition = BABYLON.Vector3.Zero();
  8415. }
  8416. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8417. return true;
  8418. }
  8419. return false;
  8420. };
  8421. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8422. if (this.parent && this.parent.getWorldMatrix) {
  8423. this.computeTransformedPosition();
  8424. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8425. return;
  8426. }
  8427. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8428. };
  8429. PointLight.prototype.needCube = function () {
  8430. return true;
  8431. };
  8432. PointLight.prototype.supportsVSM = function () {
  8433. return false;
  8434. };
  8435. PointLight.prototype.needRefreshPerFrame = function () {
  8436. return false;
  8437. };
  8438. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8439. switch (faceIndex) {
  8440. case 0:
  8441. return new BABYLON.Vector3(1, 0, 0);
  8442. case 1:
  8443. return new BABYLON.Vector3(-1, 0, 0);
  8444. case 2:
  8445. return new BABYLON.Vector3(0, -1, 0);
  8446. case 3:
  8447. return new BABYLON.Vector3(0, 1, 0);
  8448. case 4:
  8449. return new BABYLON.Vector3(0, 0, 1);
  8450. case 5:
  8451. return new BABYLON.Vector3(0, 0, -1);
  8452. }
  8453. return BABYLON.Vector3.Zero();
  8454. };
  8455. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8456. var activeCamera = this.getScene().activeCamera;
  8457. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8458. };
  8459. PointLight.prototype._getWorldMatrix = function () {
  8460. if (!this._worldMatrix) {
  8461. this._worldMatrix = BABYLON.Matrix.Identity();
  8462. }
  8463. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8464. return this._worldMatrix;
  8465. };
  8466. return PointLight;
  8467. })(BABYLON.Light);
  8468. BABYLON.PointLight = PointLight;
  8469. })(BABYLON || (BABYLON = {}));
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SpotLight = (function (_super) {
  8473. __extends(SpotLight, _super);
  8474. function SpotLight(name, position, direction, angle, exponent, scene) {
  8475. _super.call(this, name, scene);
  8476. this.position = position;
  8477. this.direction = direction;
  8478. this.angle = angle;
  8479. this.exponent = exponent;
  8480. }
  8481. SpotLight.prototype.getAbsolutePosition = function () {
  8482. return this.transformedPosition ? this.transformedPosition : this.position;
  8483. };
  8484. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8485. var activeCamera = this.getScene().activeCamera;
  8486. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8487. };
  8488. SpotLight.prototype.needCube = function () {
  8489. return false;
  8490. };
  8491. SpotLight.prototype.supportsVSM = function () {
  8492. return true;
  8493. };
  8494. SpotLight.prototype.needRefreshPerFrame = function () {
  8495. return false;
  8496. };
  8497. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8498. return this.direction;
  8499. };
  8500. SpotLight.prototype.setDirectionToTarget = function (target) {
  8501. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8502. return this.direction;
  8503. };
  8504. SpotLight.prototype.computeTransformedPosition = function () {
  8505. if (this.parent && this.parent.getWorldMatrix) {
  8506. if (!this.transformedPosition) {
  8507. this.transformedPosition = BABYLON.Vector3.Zero();
  8508. }
  8509. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8510. return true;
  8511. }
  8512. return false;
  8513. };
  8514. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8515. var normalizeDirection;
  8516. if (this.parent && this.parent.getWorldMatrix) {
  8517. if (!this._transformedDirection) {
  8518. this._transformedDirection = BABYLON.Vector3.Zero();
  8519. }
  8520. this.computeTransformedPosition();
  8521. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8522. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8523. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8524. }
  8525. else {
  8526. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8527. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8528. }
  8529. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8530. };
  8531. SpotLight.prototype._getWorldMatrix = function () {
  8532. if (!this._worldMatrix) {
  8533. this._worldMatrix = BABYLON.Matrix.Identity();
  8534. }
  8535. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8536. return this._worldMatrix;
  8537. };
  8538. return SpotLight;
  8539. })(BABYLON.Light);
  8540. BABYLON.SpotLight = SpotLight;
  8541. })(BABYLON || (BABYLON = {}));
  8542. var BABYLON;
  8543. (function (BABYLON) {
  8544. var HemisphericLight = (function (_super) {
  8545. __extends(HemisphericLight, _super);
  8546. function HemisphericLight(name, direction, scene) {
  8547. _super.call(this, name, scene);
  8548. this.direction = direction;
  8549. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8550. }
  8551. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8552. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8553. return this.direction;
  8554. };
  8555. HemisphericLight.prototype.getShadowGenerator = function () {
  8556. return null;
  8557. };
  8558. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8559. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8560. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8561. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8562. };
  8563. HemisphericLight.prototype._getWorldMatrix = function () {
  8564. if (!this._worldMatrix) {
  8565. this._worldMatrix = BABYLON.Matrix.Identity();
  8566. }
  8567. return this._worldMatrix;
  8568. };
  8569. return HemisphericLight;
  8570. })(BABYLON.Light);
  8571. BABYLON.HemisphericLight = HemisphericLight;
  8572. })(BABYLON || (BABYLON = {}));
  8573. var BABYLON;
  8574. (function (BABYLON) {
  8575. var DirectionalLight = (function (_super) {
  8576. __extends(DirectionalLight, _super);
  8577. function DirectionalLight(name, direction, scene) {
  8578. _super.call(this, name, scene);
  8579. this.direction = direction;
  8580. this.shadowOrthoScale = 0.5;
  8581. this.autoUpdateExtends = true;
  8582. // Cache
  8583. this._orthoLeft = Number.MAX_VALUE;
  8584. this._orthoRight = Number.MIN_VALUE;
  8585. this._orthoTop = Number.MIN_VALUE;
  8586. this._orthoBottom = Number.MAX_VALUE;
  8587. this.position = direction.scale(-1);
  8588. }
  8589. DirectionalLight.prototype.getAbsolutePosition = function () {
  8590. return this.transformedPosition ? this.transformedPosition : this.position;
  8591. };
  8592. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8593. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8594. return this.direction;
  8595. };
  8596. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8597. var activeCamera = this.getScene().activeCamera;
  8598. // Check extends
  8599. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8600. var tempVector3 = BABYLON.Vector3.Zero();
  8601. this._orthoLeft = Number.MAX_VALUE;
  8602. this._orthoRight = Number.MIN_VALUE;
  8603. this._orthoTop = Number.MIN_VALUE;
  8604. this._orthoBottom = Number.MAX_VALUE;
  8605. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8606. var mesh = renderList[meshIndex];
  8607. if (!mesh) {
  8608. continue;
  8609. }
  8610. var boundingInfo = mesh.getBoundingInfo();
  8611. if (!boundingInfo) {
  8612. continue;
  8613. }
  8614. var boundingBox = boundingInfo.boundingBox;
  8615. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8616. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8617. if (tempVector3.x < this._orthoLeft)
  8618. this._orthoLeft = tempVector3.x;
  8619. if (tempVector3.y < this._orthoBottom)
  8620. this._orthoBottom = tempVector3.y;
  8621. if (tempVector3.x > this._orthoRight)
  8622. this._orthoRight = tempVector3.x;
  8623. if (tempVector3.y > this._orthoTop)
  8624. this._orthoTop = tempVector3.y;
  8625. }
  8626. }
  8627. }
  8628. var xOffset = this._orthoRight - this._orthoLeft;
  8629. var yOffset = this._orthoTop - this._orthoBottom;
  8630. 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);
  8631. };
  8632. DirectionalLight.prototype.supportsVSM = function () {
  8633. return true;
  8634. };
  8635. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8636. return true;
  8637. };
  8638. DirectionalLight.prototype.needCube = function () {
  8639. return false;
  8640. };
  8641. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8642. return this.direction;
  8643. };
  8644. DirectionalLight.prototype.computeTransformedPosition = function () {
  8645. if (this.parent && this.parent.getWorldMatrix) {
  8646. if (!this.transformedPosition) {
  8647. this.transformedPosition = BABYLON.Vector3.Zero();
  8648. }
  8649. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8650. return true;
  8651. }
  8652. return false;
  8653. };
  8654. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8655. if (this.parent && this.parent.getWorldMatrix) {
  8656. if (!this._transformedDirection) {
  8657. this._transformedDirection = BABYLON.Vector3.Zero();
  8658. }
  8659. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8660. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8661. return;
  8662. }
  8663. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8664. };
  8665. DirectionalLight.prototype._getWorldMatrix = function () {
  8666. if (!this._worldMatrix) {
  8667. this._worldMatrix = BABYLON.Matrix.Identity();
  8668. }
  8669. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8670. return this._worldMatrix;
  8671. };
  8672. return DirectionalLight;
  8673. })(BABYLON.Light);
  8674. BABYLON.DirectionalLight = DirectionalLight;
  8675. })(BABYLON || (BABYLON = {}));
  8676. var BABYLON;
  8677. (function (BABYLON) {
  8678. var ShadowGenerator = (function () {
  8679. function ShadowGenerator(mapSize, light) {
  8680. var _this = this;
  8681. // Members
  8682. this._filter = ShadowGenerator.FILTER_NONE;
  8683. this.blurScale = 2;
  8684. this._blurBoxOffset = 0;
  8685. this._bias = 0.00005;
  8686. this._lightDirection = BABYLON.Vector3.Zero();
  8687. this._darkness = 0;
  8688. this._transparencyShadow = false;
  8689. this._viewMatrix = BABYLON.Matrix.Zero();
  8690. this._projectionMatrix = BABYLON.Matrix.Zero();
  8691. this._transformMatrix = BABYLON.Matrix.Zero();
  8692. this._worldViewProjection = BABYLON.Matrix.Zero();
  8693. this._currentFaceIndex = 0;
  8694. this._currentFaceIndexCache = 0;
  8695. this._light = light;
  8696. this._scene = light.getScene();
  8697. this._mapSize = mapSize;
  8698. light._shadowGenerator = this;
  8699. // Render target
  8700. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8701. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8702. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8703. this._shadowMap.anisotropicFilteringLevel = 1;
  8704. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8705. this._shadowMap.renderParticles = false;
  8706. this._shadowMap.onBeforeRender = function (faceIndex) {
  8707. _this._currentFaceIndex = faceIndex;
  8708. };
  8709. this._shadowMap.onAfterUnbind = function () {
  8710. if (!_this.useBlurVarianceShadowMap) {
  8711. return;
  8712. }
  8713. if (!_this._shadowMap2) {
  8714. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8715. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8716. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8717. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8718. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8719. _this._downSamplePostprocess.onApply = function (effect) {
  8720. effect.setTexture("textureSampler", _this._shadowMap);
  8721. };
  8722. _this.blurBoxOffset = 1;
  8723. }
  8724. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8725. };
  8726. // Custom render function
  8727. var renderSubMesh = function (subMesh) {
  8728. var mesh = subMesh.getRenderingMesh();
  8729. var scene = _this._scene;
  8730. var engine = scene.getEngine();
  8731. // Culling
  8732. engine.setState(subMesh.getMaterial().backFaceCulling);
  8733. // Managing instances
  8734. var batch = mesh._getInstancesRenderList(subMesh._id);
  8735. if (batch.mustReturn) {
  8736. return;
  8737. }
  8738. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8739. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8740. engine.enableEffect(_this._effect);
  8741. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8742. var material = subMesh.getMaterial();
  8743. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8744. // Alpha test
  8745. if (material && material.needAlphaTesting()) {
  8746. var alphaTexture = material.getAlphaTestTexture();
  8747. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8748. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8749. }
  8750. // Bones
  8751. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8752. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8753. }
  8754. // Draw
  8755. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8756. }
  8757. else {
  8758. // Need to reset refresh rate of the shadowMap
  8759. _this._shadowMap.resetRefreshCounter();
  8760. }
  8761. };
  8762. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8763. var index;
  8764. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8765. renderSubMesh(opaqueSubMeshes.data[index]);
  8766. }
  8767. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8768. renderSubMesh(alphaTestSubMeshes.data[index]);
  8769. }
  8770. if (_this._transparencyShadow) {
  8771. for (index = 0; index < transparentSubMeshes.length; index++) {
  8772. renderSubMesh(transparentSubMeshes.data[index]);
  8773. }
  8774. }
  8775. };
  8776. this._shadowMap.onClear = function (engine) {
  8777. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8778. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8779. }
  8780. else {
  8781. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8782. }
  8783. };
  8784. }
  8785. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8786. // Static
  8787. get: function () {
  8788. return ShadowGenerator._FILTER_NONE;
  8789. },
  8790. enumerable: true,
  8791. configurable: true
  8792. });
  8793. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8794. get: function () {
  8795. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8796. },
  8797. enumerable: true,
  8798. configurable: true
  8799. });
  8800. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8801. get: function () {
  8802. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8803. },
  8804. enumerable: true,
  8805. configurable: true
  8806. });
  8807. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8808. get: function () {
  8809. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8810. },
  8811. enumerable: true,
  8812. configurable: true
  8813. });
  8814. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8815. get: function () {
  8816. return this._bias;
  8817. },
  8818. set: function (bias) {
  8819. this._bias = bias;
  8820. },
  8821. enumerable: true,
  8822. configurable: true
  8823. });
  8824. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8825. get: function () {
  8826. return this._blurBoxOffset;
  8827. },
  8828. set: function (value) {
  8829. var _this = this;
  8830. if (this._blurBoxOffset === value) {
  8831. return;
  8832. }
  8833. this._blurBoxOffset = value;
  8834. if (this._boxBlurPostprocess) {
  8835. this._boxBlurPostprocess.dispose();
  8836. }
  8837. 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);
  8838. this._boxBlurPostprocess.onApply = function (effect) {
  8839. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8840. };
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8846. get: function () {
  8847. return this._filter;
  8848. },
  8849. set: function (value) {
  8850. if (this._filter === value) {
  8851. return;
  8852. }
  8853. this._filter = value;
  8854. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8855. this._shadowMap.anisotropicFilteringLevel = 16;
  8856. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8857. }
  8858. else {
  8859. this._shadowMap.anisotropicFilteringLevel = 1;
  8860. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8861. }
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8867. get: function () {
  8868. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8869. },
  8870. set: function (value) {
  8871. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8872. },
  8873. enumerable: true,
  8874. configurable: true
  8875. });
  8876. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8877. get: function () {
  8878. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8879. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8880. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8881. },
  8882. set: function (value) {
  8883. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8889. get: function () {
  8890. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8891. },
  8892. set: function (value) {
  8893. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8894. },
  8895. enumerable: true,
  8896. configurable: true
  8897. });
  8898. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8899. var defines = [];
  8900. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8901. defines.push("#define VSM");
  8902. }
  8903. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8904. var mesh = subMesh.getMesh();
  8905. var material = subMesh.getMaterial();
  8906. // Alpha test
  8907. if (material && material.needAlphaTesting()) {
  8908. defines.push("#define ALPHATEST");
  8909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8910. attribs.push(BABYLON.VertexBuffer.UVKind);
  8911. defines.push("#define UV1");
  8912. }
  8913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8914. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8915. defines.push("#define UV2");
  8916. }
  8917. }
  8918. // Bones
  8919. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8920. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8921. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8922. defines.push("#define BONES");
  8923. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8924. }
  8925. // Instances
  8926. if (useInstances) {
  8927. defines.push("#define INSTANCES");
  8928. attribs.push("world0");
  8929. attribs.push("world1");
  8930. attribs.push("world2");
  8931. attribs.push("world3");
  8932. }
  8933. // Get correct effect
  8934. var join = defines.join("\n");
  8935. if (this._cachedDefines !== join) {
  8936. this._cachedDefines = join;
  8937. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8938. }
  8939. return this._effect.isReady();
  8940. };
  8941. ShadowGenerator.prototype.getShadowMap = function () {
  8942. return this._shadowMap;
  8943. };
  8944. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8945. if (this._shadowMap2) {
  8946. return this._shadowMap2;
  8947. }
  8948. return this._shadowMap;
  8949. };
  8950. ShadowGenerator.prototype.getLight = function () {
  8951. return this._light;
  8952. };
  8953. // Methods
  8954. ShadowGenerator.prototype.getTransformMatrix = function () {
  8955. var scene = this._scene;
  8956. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  8957. return this._transformMatrix;
  8958. }
  8959. this._currentRenderID = scene.getRenderId();
  8960. this._currentFaceIndexCache = this._currentFaceIndex;
  8961. var lightPosition = this._light.position;
  8962. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  8963. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  8964. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8965. }
  8966. if (this._light.computeTransformedPosition()) {
  8967. lightPosition = this._light.transformedPosition;
  8968. }
  8969. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8970. this._cachedPosition = lightPosition.clone();
  8971. this._cachedDirection = this._lightDirection.clone();
  8972. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8973. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8974. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8975. }
  8976. return this._transformMatrix;
  8977. };
  8978. ShadowGenerator.prototype.getDarkness = function () {
  8979. return this._darkness;
  8980. };
  8981. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8982. if (darkness >= 1.0)
  8983. this._darkness = 1.0;
  8984. else if (darkness <= 0.0)
  8985. this._darkness = 0.0;
  8986. else
  8987. this._darkness = darkness;
  8988. };
  8989. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8990. this._transparencyShadow = hasShadow;
  8991. };
  8992. ShadowGenerator.prototype._packHalf = function (depth) {
  8993. var scale = depth * 255.0;
  8994. var fract = scale - Math.floor(scale);
  8995. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8996. };
  8997. ShadowGenerator.prototype.dispose = function () {
  8998. this._shadowMap.dispose();
  8999. if (this._shadowMap2) {
  9000. this._shadowMap2.dispose();
  9001. }
  9002. if (this._downSamplePostprocess) {
  9003. this._downSamplePostprocess.dispose();
  9004. }
  9005. if (this._boxBlurPostprocess) {
  9006. this._boxBlurPostprocess.dispose();
  9007. }
  9008. };
  9009. ShadowGenerator._FILTER_NONE = 0;
  9010. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9011. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9012. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9013. return ShadowGenerator;
  9014. })();
  9015. BABYLON.ShadowGenerator = ShadowGenerator;
  9016. })(BABYLON || (BABYLON = {}));
  9017. var BABYLON;
  9018. (function (BABYLON) {
  9019. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9020. if (boxMin.x > sphereCenter.x + sphereRadius)
  9021. return false;
  9022. if (sphereCenter.x - sphereRadius > boxMax.x)
  9023. return false;
  9024. if (boxMin.y > sphereCenter.y + sphereRadius)
  9025. return false;
  9026. if (sphereCenter.y - sphereRadius > boxMax.y)
  9027. return false;
  9028. if (boxMin.z > sphereCenter.z + sphereRadius)
  9029. return false;
  9030. if (sphereCenter.z - sphereRadius > boxMax.z)
  9031. return false;
  9032. return true;
  9033. };
  9034. var getLowestRoot = function (a, b, c, maxR) {
  9035. var determinant = b * b - 4.0 * a * c;
  9036. var result = { root: 0, found: false };
  9037. if (determinant < 0)
  9038. return result;
  9039. var sqrtD = Math.sqrt(determinant);
  9040. var r1 = (-b - sqrtD) / (2.0 * a);
  9041. var r2 = (-b + sqrtD) / (2.0 * a);
  9042. if (r1 > r2) {
  9043. var temp = r2;
  9044. r2 = r1;
  9045. r1 = temp;
  9046. }
  9047. if (r1 > 0 && r1 < maxR) {
  9048. result.root = r1;
  9049. result.found = true;
  9050. return result;
  9051. }
  9052. if (r2 > 0 && r2 < maxR) {
  9053. result.root = r2;
  9054. result.found = true;
  9055. return result;
  9056. }
  9057. return result;
  9058. };
  9059. var Collider = (function () {
  9060. function Collider() {
  9061. this.radius = new BABYLON.Vector3(1, 1, 1);
  9062. this.retry = 0;
  9063. this.basePointWorld = BABYLON.Vector3.Zero();
  9064. this.velocityWorld = BABYLON.Vector3.Zero();
  9065. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9066. this._collisionPoint = BABYLON.Vector3.Zero();
  9067. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9068. this._tempVector = BABYLON.Vector3.Zero();
  9069. this._tempVector2 = BABYLON.Vector3.Zero();
  9070. this._tempVector3 = BABYLON.Vector3.Zero();
  9071. this._tempVector4 = BABYLON.Vector3.Zero();
  9072. this._edge = BABYLON.Vector3.Zero();
  9073. this._baseToVertex = BABYLON.Vector3.Zero();
  9074. this._destinationPoint = BABYLON.Vector3.Zero();
  9075. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9076. this._displacementVector = BABYLON.Vector3.Zero();
  9077. }
  9078. // Methods
  9079. Collider.prototype._initialize = function (source, dir, e) {
  9080. this.velocity = dir;
  9081. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9082. this.basePoint = source;
  9083. source.multiplyToRef(this.radius, this.basePointWorld);
  9084. dir.multiplyToRef(this.radius, this.velocityWorld);
  9085. this.velocityWorldLength = this.velocityWorld.length();
  9086. this.epsilon = e;
  9087. this.collisionFound = false;
  9088. };
  9089. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9090. pa.subtractToRef(point, this._tempVector);
  9091. pb.subtractToRef(point, this._tempVector2);
  9092. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9093. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9094. if (d < 0)
  9095. return false;
  9096. pc.subtractToRef(point, this._tempVector3);
  9097. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9098. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9099. if (d < 0)
  9100. return false;
  9101. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9102. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9103. return d >= 0;
  9104. };
  9105. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9106. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9107. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9108. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9109. return false;
  9110. }
  9111. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9112. return false;
  9113. return true;
  9114. };
  9115. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9116. var t0;
  9117. var embeddedInPlane = false;
  9118. //defensive programming, actually not needed.
  9119. if (!trianglePlaneArray) {
  9120. trianglePlaneArray = [];
  9121. }
  9122. if (!trianglePlaneArray[faceIndex]) {
  9123. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9124. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9125. }
  9126. var trianglePlane = trianglePlaneArray[faceIndex];
  9127. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9128. return;
  9129. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9130. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9131. if (normalDotVelocity == 0) {
  9132. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9133. return;
  9134. embeddedInPlane = true;
  9135. t0 = 0;
  9136. }
  9137. else {
  9138. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9139. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9140. if (t0 > t1) {
  9141. var temp = t1;
  9142. t1 = t0;
  9143. t0 = temp;
  9144. }
  9145. if (t0 > 1.0 || t1 < 0.0)
  9146. return;
  9147. if (t0 < 0)
  9148. t0 = 0;
  9149. if (t0 > 1.0)
  9150. t0 = 1.0;
  9151. }
  9152. this._collisionPoint.copyFromFloats(0, 0, 0);
  9153. var found = false;
  9154. var t = 1.0;
  9155. if (!embeddedInPlane) {
  9156. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9157. this.velocity.scaleToRef(t0, this._tempVector);
  9158. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9159. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9160. found = true;
  9161. t = t0;
  9162. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9163. }
  9164. }
  9165. if (!found) {
  9166. var velocitySquaredLength = this.velocity.lengthSquared();
  9167. var a = velocitySquaredLength;
  9168. this.basePoint.subtractToRef(p1, this._tempVector);
  9169. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9170. var c = this._tempVector.lengthSquared() - 1.0;
  9171. var lowestRoot = getLowestRoot(a, b, c, t);
  9172. if (lowestRoot.found) {
  9173. t = lowestRoot.root;
  9174. found = true;
  9175. this._collisionPoint.copyFrom(p1);
  9176. }
  9177. this.basePoint.subtractToRef(p2, this._tempVector);
  9178. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9179. c = this._tempVector.lengthSquared() - 1.0;
  9180. lowestRoot = getLowestRoot(a, b, c, t);
  9181. if (lowestRoot.found) {
  9182. t = lowestRoot.root;
  9183. found = true;
  9184. this._collisionPoint.copyFrom(p2);
  9185. }
  9186. this.basePoint.subtractToRef(p3, this._tempVector);
  9187. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9188. c = this._tempVector.lengthSquared() - 1.0;
  9189. lowestRoot = getLowestRoot(a, b, c, t);
  9190. if (lowestRoot.found) {
  9191. t = lowestRoot.root;
  9192. found = true;
  9193. this._collisionPoint.copyFrom(p3);
  9194. }
  9195. p2.subtractToRef(p1, this._edge);
  9196. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9197. var edgeSquaredLength = this._edge.lengthSquared();
  9198. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9199. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9200. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9201. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9202. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9203. lowestRoot = getLowestRoot(a, b, c, t);
  9204. if (lowestRoot.found) {
  9205. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9206. if (f >= 0.0 && f <= 1.0) {
  9207. t = lowestRoot.root;
  9208. found = true;
  9209. this._edge.scaleInPlace(f);
  9210. p1.addToRef(this._edge, this._collisionPoint);
  9211. }
  9212. }
  9213. p3.subtractToRef(p2, this._edge);
  9214. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9215. edgeSquaredLength = this._edge.lengthSquared();
  9216. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9217. 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. 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. p2.addToRef(this._edge, this._collisionPoint);
  9229. }
  9230. }
  9231. p1.subtractToRef(p3, this._edge);
  9232. p3.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. p3.addToRef(this._edge, this._collisionPoint);
  9247. }
  9248. }
  9249. }
  9250. if (found) {
  9251. var distToCollision = t * this.velocity.length();
  9252. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9253. if (!this.intersectionPoint) {
  9254. this.intersectionPoint = this._collisionPoint.clone();
  9255. }
  9256. else {
  9257. this.intersectionPoint.copyFrom(this._collisionPoint);
  9258. }
  9259. this.nearestDistance = distToCollision;
  9260. this.collisionFound = true;
  9261. }
  9262. }
  9263. };
  9264. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9265. for (var i = indexStart; i < indexEnd; i += 3) {
  9266. var p1 = pts[indices[i] - decal];
  9267. var p2 = pts[indices[i + 1] - decal];
  9268. var p3 = pts[indices[i + 2] - decal];
  9269. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9270. }
  9271. };
  9272. Collider.prototype._getResponse = function (pos, vel) {
  9273. pos.addToRef(vel, this._destinationPoint);
  9274. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9275. this.basePoint.addToRef(vel, pos);
  9276. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9277. this._slidePlaneNormal.normalize();
  9278. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9279. pos.addInPlace(this._displacementVector);
  9280. this.intersectionPoint.addInPlace(this._displacementVector);
  9281. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9282. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9283. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9284. };
  9285. return Collider;
  9286. })();
  9287. BABYLON.Collider = Collider;
  9288. })(BABYLON || (BABYLON = {}));
  9289. var BABYLON;
  9290. (function (BABYLON) {
  9291. //WebWorker code will be inserted to this variable.
  9292. BABYLON.CollisionWorker = "";
  9293. (function (WorkerTaskType) {
  9294. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9295. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9296. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9297. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9298. var WorkerTaskType = BABYLON.WorkerTaskType;
  9299. (function (WorkerReplyType) {
  9300. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9301. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9302. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9303. var WorkerReplyType = BABYLON.WorkerReplyType;
  9304. var CollisionCoordinatorWorker = (function () {
  9305. function CollisionCoordinatorWorker() {
  9306. var _this = this;
  9307. this._scaledPosition = BABYLON.Vector3.Zero();
  9308. this._scaledVelocity = BABYLON.Vector3.Zero();
  9309. this.onMeshUpdated = function (mesh) {
  9310. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9311. };
  9312. this.onGeometryUpdated = function (geometry) {
  9313. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9314. };
  9315. this._afterRender = function () {
  9316. if (!_this._init)
  9317. return;
  9318. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9319. return;
  9320. }
  9321. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9322. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9323. if (_this._runningUpdated > 4) {
  9324. return;
  9325. }
  9326. ++_this._runningUpdated;
  9327. var payload = {
  9328. updatedMeshes: _this._addUpdateMeshesList,
  9329. updatedGeometries: _this._addUpdateGeometriesList,
  9330. removedGeometries: _this._toRemoveGeometryArray,
  9331. removedMeshes: _this._toRemoveMeshesArray
  9332. };
  9333. var message = {
  9334. payload: payload,
  9335. taskType: WorkerTaskType.UPDATE
  9336. };
  9337. var serializable = [];
  9338. for (var id in payload.updatedGeometries) {
  9339. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9340. //prepare transferables
  9341. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9342. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9343. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9344. }
  9345. }
  9346. _this._worker.postMessage(message, serializable);
  9347. _this._addUpdateMeshesList = {};
  9348. _this._addUpdateGeometriesList = {};
  9349. _this._toRemoveGeometryArray = [];
  9350. _this._toRemoveMeshesArray = [];
  9351. };
  9352. this._onMessageFromWorker = function (e) {
  9353. var returnData = e.data;
  9354. if (returnData.error != WorkerReplyType.SUCCESS) {
  9355. //TODO what errors can be returned from the worker?
  9356. BABYLON.Tools.Warn("error returned from worker!");
  9357. return;
  9358. }
  9359. switch (returnData.taskType) {
  9360. case WorkerTaskType.INIT:
  9361. _this._init = true;
  9362. //Update the worked with ALL of the scene's current state
  9363. _this._scene.meshes.forEach(function (mesh) {
  9364. _this.onMeshAdded(mesh);
  9365. });
  9366. _this._scene.getGeometries().forEach(function (geometry) {
  9367. _this.onGeometryAdded(geometry);
  9368. });
  9369. break;
  9370. case WorkerTaskType.UPDATE:
  9371. _this._runningUpdated--;
  9372. break;
  9373. case WorkerTaskType.COLLIDE:
  9374. _this._runningCollisionTask = false;
  9375. var returnPayload = returnData.payload;
  9376. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9377. return;
  9378. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9379. //cleanup
  9380. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9381. break;
  9382. }
  9383. };
  9384. this._collisionsCallbackArray = [];
  9385. this._init = false;
  9386. this._runningUpdated = 0;
  9387. this._runningCollisionTask = false;
  9388. this._addUpdateMeshesList = {};
  9389. this._addUpdateGeometriesList = {};
  9390. this._toRemoveGeometryArray = [];
  9391. this._toRemoveMeshesArray = [];
  9392. }
  9393. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9394. if (!this._init)
  9395. return;
  9396. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9397. return;
  9398. position.divideToRef(collider.radius, this._scaledPosition);
  9399. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9400. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9401. var payload = {
  9402. collider: {
  9403. position: this._scaledPosition.asArray(),
  9404. velocity: this._scaledVelocity.asArray(),
  9405. radius: collider.radius.asArray()
  9406. },
  9407. collisionId: collisionIndex,
  9408. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9409. maximumRetry: maximumRetry
  9410. };
  9411. var message = {
  9412. payload: payload,
  9413. taskType: WorkerTaskType.COLLIDE
  9414. };
  9415. this._worker.postMessage(message);
  9416. };
  9417. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9418. this._scene = scene;
  9419. this._scene.registerAfterRender(this._afterRender);
  9420. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9421. this._worker = new Worker(workerUrl);
  9422. this._worker.onmessage = this._onMessageFromWorker;
  9423. var message = {
  9424. payload: {},
  9425. taskType: WorkerTaskType.INIT
  9426. };
  9427. this._worker.postMessage(message);
  9428. };
  9429. CollisionCoordinatorWorker.prototype.destroy = function () {
  9430. this._scene.unregisterAfterRender(this._afterRender);
  9431. this._worker.terminate();
  9432. };
  9433. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9434. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9435. this.onMeshUpdated(mesh);
  9436. };
  9437. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9438. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9439. };
  9440. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9441. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9442. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9443. this.onGeometryUpdated(geometry);
  9444. };
  9445. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9446. this._toRemoveGeometryArray.push(geometry.id);
  9447. };
  9448. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9449. var submeshes = [];
  9450. if (mesh.subMeshes) {
  9451. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9452. return {
  9453. position: idx,
  9454. verticesStart: sm.verticesStart,
  9455. verticesCount: sm.verticesCount,
  9456. indexStart: sm.indexStart,
  9457. indexCount: sm.indexCount,
  9458. hasMaterial: !!sm.getMaterial(),
  9459. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9460. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9461. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9462. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9463. };
  9464. });
  9465. }
  9466. var geometryId = null;
  9467. if (mesh instanceof BABYLON.Mesh) {
  9468. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9469. }
  9470. else if (mesh instanceof BABYLON.InstancedMesh) {
  9471. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9472. }
  9473. return {
  9474. uniqueId: mesh.uniqueId,
  9475. id: mesh.id,
  9476. name: mesh.name,
  9477. geometryId: geometryId,
  9478. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9479. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9480. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9481. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9482. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9483. subMeshes: submeshes,
  9484. checkCollisions: mesh.checkCollisions
  9485. };
  9486. };
  9487. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9488. return {
  9489. id: geometry.id,
  9490. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9491. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9492. indices: new Int32Array(geometry.getIndices() || []),
  9493. };
  9494. };
  9495. return CollisionCoordinatorWorker;
  9496. })();
  9497. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9498. var CollisionCoordinatorLegacy = (function () {
  9499. function CollisionCoordinatorLegacy() {
  9500. this._scaledPosition = BABYLON.Vector3.Zero();
  9501. this._scaledVelocity = BABYLON.Vector3.Zero();
  9502. this._finalPosition = BABYLON.Vector3.Zero();
  9503. }
  9504. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9505. position.divideToRef(collider.radius, this._scaledPosition);
  9506. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9507. collider.collidedMesh = null;
  9508. collider.retry = 0;
  9509. collider.initialVelocity = this._scaledVelocity;
  9510. collider.initialPosition = this._scaledPosition;
  9511. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9512. this._finalPosition.multiplyInPlace(collider.radius);
  9513. //run the callback
  9514. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9515. };
  9516. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9517. this._scene = scene;
  9518. };
  9519. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9520. //Legacy need no destruction method.
  9521. };
  9522. //No update in legacy mode
  9523. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9524. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9525. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9526. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9527. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9528. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9529. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9530. if (excludedMesh === void 0) { excludedMesh = null; }
  9531. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9532. if (collider.retry >= maximumRetry) {
  9533. finalPosition.copyFrom(position);
  9534. return;
  9535. }
  9536. collider._initialize(position, velocity, closeDistance);
  9537. // Check all meshes
  9538. for (var index = 0; index < this._scene.meshes.length; index++) {
  9539. var mesh = this._scene.meshes[index];
  9540. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9541. mesh._checkCollision(collider);
  9542. }
  9543. }
  9544. if (!collider.collisionFound) {
  9545. position.addToRef(velocity, finalPosition);
  9546. return;
  9547. }
  9548. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9549. collider._getResponse(position, velocity);
  9550. }
  9551. if (velocity.length() <= closeDistance) {
  9552. finalPosition.copyFrom(position);
  9553. return;
  9554. }
  9555. collider.retry++;
  9556. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9557. };
  9558. return CollisionCoordinatorLegacy;
  9559. })();
  9560. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9561. })(BABYLON || (BABYLON = {}));
  9562. var BABYLON;
  9563. (function (BABYLON) {
  9564. var VRCameraMetrics = (function () {
  9565. function VRCameraMetrics() {
  9566. this.compensateDistortion = true;
  9567. }
  9568. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9569. get: function () {
  9570. return this.hResolution / (2 * this.vResolution);
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9576. get: function () {
  9577. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9583. get: function () {
  9584. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9585. var h = (4 * meters) / this.hScreenSize;
  9586. return BABYLON.Matrix.Translation(h, 0, 0);
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9592. get: function () {
  9593. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9594. var h = (4 * meters) / this.hScreenSize;
  9595. return BABYLON.Matrix.Translation(-h, 0, 0);
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9601. get: function () {
  9602. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9608. get: function () {
  9609. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. VRCameraMetrics.GetDefault = function () {
  9615. var result = new VRCameraMetrics();
  9616. result.hResolution = 1280;
  9617. result.vResolution = 800;
  9618. result.hScreenSize = 0.149759993;
  9619. result.vScreenSize = 0.0935999975;
  9620. result.vScreenCenter = 0.0467999987,
  9621. result.eyeToScreenDistance = 0.0410000011;
  9622. result.lensSeparationDistance = 0.0635000020;
  9623. result.interpupillaryDistance = 0.0640000030;
  9624. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9625. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9626. result.postProcessScaleFactor = 1.714605507808412;
  9627. result.lensCenterOffset = 0.151976421;
  9628. return result;
  9629. };
  9630. return VRCameraMetrics;
  9631. })();
  9632. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9633. var Camera = (function (_super) {
  9634. __extends(Camera, _super);
  9635. function Camera(name, position, scene) {
  9636. _super.call(this, name, scene);
  9637. this.position = position;
  9638. // Members
  9639. this.upVector = BABYLON.Vector3.Up();
  9640. this.orthoLeft = null;
  9641. this.orthoRight = null;
  9642. this.orthoBottom = null;
  9643. this.orthoTop = null;
  9644. this.fov = 0.8;
  9645. this.minZ = 1.0;
  9646. this.maxZ = 10000.0;
  9647. this.inertia = 0.9;
  9648. this.mode = Camera.PERSPECTIVE_CAMERA;
  9649. this.isIntermediate = false;
  9650. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9651. this.layerMask = 0x0FFFFFFF;
  9652. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9653. // Camera rig members
  9654. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9655. this._rigCameras = new Array();
  9656. // Cache
  9657. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9658. this._projectionMatrix = new BABYLON.Matrix();
  9659. this._postProcesses = new Array();
  9660. this._postProcessesTakenIndices = [];
  9661. this._activeMeshes = new BABYLON.SmartArray(256);
  9662. this._globalPosition = BABYLON.Vector3.Zero();
  9663. scene.addCamera(this);
  9664. if (!scene.activeCamera) {
  9665. scene.activeCamera = this;
  9666. }
  9667. }
  9668. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9669. get: function () {
  9670. return Camera._PERSPECTIVE_CAMERA;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9676. get: function () {
  9677. return Camera._ORTHOGRAPHIC_CAMERA;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9683. get: function () {
  9684. return Camera._FOVMODE_VERTICAL_FIXED;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9690. get: function () {
  9691. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9692. },
  9693. enumerable: true,
  9694. configurable: true
  9695. });
  9696. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9697. get: function () {
  9698. return Camera._RIG_MODE_NONE;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9704. get: function () {
  9705. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9711. get: function () {
  9712. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9713. },
  9714. enumerable: true,
  9715. configurable: true
  9716. });
  9717. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9718. get: function () {
  9719. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9720. },
  9721. enumerable: true,
  9722. configurable: true
  9723. });
  9724. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9725. get: function () {
  9726. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9732. get: function () {
  9733. return Camera._RIG_MODE_VR;
  9734. },
  9735. enumerable: true,
  9736. configurable: true
  9737. });
  9738. Object.defineProperty(Camera.prototype, "globalPosition", {
  9739. get: function () {
  9740. return this._globalPosition;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Camera.prototype.getActiveMeshes = function () {
  9746. return this._activeMeshes;
  9747. };
  9748. Camera.prototype.isActiveMesh = function (mesh) {
  9749. return (this._activeMeshes.indexOf(mesh) !== -1);
  9750. };
  9751. //Cache
  9752. Camera.prototype._initCache = function () {
  9753. _super.prototype._initCache.call(this);
  9754. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9755. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9756. this._cache.mode = undefined;
  9757. this._cache.minZ = undefined;
  9758. this._cache.maxZ = undefined;
  9759. this._cache.fov = undefined;
  9760. this._cache.aspectRatio = undefined;
  9761. this._cache.orthoLeft = undefined;
  9762. this._cache.orthoRight = undefined;
  9763. this._cache.orthoBottom = undefined;
  9764. this._cache.orthoTop = undefined;
  9765. this._cache.renderWidth = undefined;
  9766. this._cache.renderHeight = undefined;
  9767. };
  9768. Camera.prototype._updateCache = function (ignoreParentClass) {
  9769. if (!ignoreParentClass) {
  9770. _super.prototype._updateCache.call(this);
  9771. }
  9772. var engine = this.getEngine();
  9773. this._cache.position.copyFrom(this.position);
  9774. this._cache.upVector.copyFrom(this.upVector);
  9775. this._cache.mode = this.mode;
  9776. this._cache.minZ = this.minZ;
  9777. this._cache.maxZ = this.maxZ;
  9778. this._cache.fov = this.fov;
  9779. this._cache.aspectRatio = engine.getAspectRatio(this);
  9780. this._cache.orthoLeft = this.orthoLeft;
  9781. this._cache.orthoRight = this.orthoRight;
  9782. this._cache.orthoBottom = this.orthoBottom;
  9783. this._cache.orthoTop = this.orthoTop;
  9784. this._cache.renderWidth = engine.getRenderWidth();
  9785. this._cache.renderHeight = engine.getRenderHeight();
  9786. };
  9787. Camera.prototype._updateFromScene = function () {
  9788. this.updateCache();
  9789. this._update();
  9790. };
  9791. // Synchronized
  9792. Camera.prototype._isSynchronized = function () {
  9793. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9794. };
  9795. Camera.prototype._isSynchronizedViewMatrix = function () {
  9796. if (!_super.prototype._isSynchronized.call(this))
  9797. return false;
  9798. return this._cache.position.equals(this.position)
  9799. && this._cache.upVector.equals(this.upVector)
  9800. && this.isSynchronizedWithParent();
  9801. };
  9802. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9803. var check = this._cache.mode === this.mode
  9804. && this._cache.minZ === this.minZ
  9805. && this._cache.maxZ === this.maxZ;
  9806. if (!check) {
  9807. return false;
  9808. }
  9809. var engine = this.getEngine();
  9810. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9811. check = this._cache.fov === this.fov
  9812. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9813. }
  9814. else {
  9815. check = this._cache.orthoLeft === this.orthoLeft
  9816. && this._cache.orthoRight === this.orthoRight
  9817. && this._cache.orthoBottom === this.orthoBottom
  9818. && this._cache.orthoTop === this.orthoTop
  9819. && this._cache.renderWidth === engine.getRenderWidth()
  9820. && this._cache.renderHeight === engine.getRenderHeight();
  9821. }
  9822. return check;
  9823. };
  9824. // Controls
  9825. Camera.prototype.attachControl = function (element) {
  9826. };
  9827. Camera.prototype.detachControl = function (element) {
  9828. };
  9829. Camera.prototype._update = function () {
  9830. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9831. this._updateRigCameras();
  9832. }
  9833. this._checkInputs();
  9834. };
  9835. Camera.prototype._checkInputs = function () {
  9836. };
  9837. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9838. if (insertAt === void 0) { insertAt = null; }
  9839. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9840. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9841. return 0;
  9842. }
  9843. if (insertAt == null || insertAt < 0) {
  9844. this._postProcesses.push(postProcess);
  9845. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9846. return this._postProcesses.length - 1;
  9847. }
  9848. var add = 0;
  9849. var i;
  9850. var start;
  9851. if (this._postProcesses[insertAt]) {
  9852. start = this._postProcesses.length - 1;
  9853. for (i = start; i >= insertAt + 1; --i) {
  9854. this._postProcesses[i + 1] = this._postProcesses[i];
  9855. }
  9856. add = 1;
  9857. }
  9858. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9859. if (this._postProcessesTakenIndices[i] < insertAt) {
  9860. continue;
  9861. }
  9862. start = this._postProcessesTakenIndices.length - 1;
  9863. for (var j = start; j >= i; --j) {
  9864. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9865. }
  9866. this._postProcessesTakenIndices[i] = insertAt;
  9867. break;
  9868. }
  9869. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9870. this._postProcessesTakenIndices.push(insertAt);
  9871. }
  9872. var result = insertAt + add;
  9873. this._postProcesses[result] = postProcess;
  9874. return result;
  9875. };
  9876. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9877. if (atIndices === void 0) { atIndices = null; }
  9878. var result = [];
  9879. var i;
  9880. var index;
  9881. if (!atIndices) {
  9882. var length = this._postProcesses.length;
  9883. for (i = 0; i < length; i++) {
  9884. if (this._postProcesses[i] !== postProcess) {
  9885. continue;
  9886. }
  9887. delete this._postProcesses[i];
  9888. index = this._postProcessesTakenIndices.indexOf(i);
  9889. this._postProcessesTakenIndices.splice(index, 1);
  9890. }
  9891. }
  9892. else {
  9893. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9894. for (i = 0; i < atIndices.length; i++) {
  9895. var foundPostProcess = this._postProcesses[atIndices[i]];
  9896. if (foundPostProcess !== postProcess) {
  9897. result.push(i);
  9898. continue;
  9899. }
  9900. delete this._postProcesses[atIndices[i]];
  9901. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9902. this._postProcessesTakenIndices.splice(index, 1);
  9903. }
  9904. }
  9905. return result;
  9906. };
  9907. Camera.prototype.getWorldMatrix = function () {
  9908. if (!this._worldMatrix) {
  9909. this._worldMatrix = BABYLON.Matrix.Identity();
  9910. }
  9911. var viewMatrix = this.getViewMatrix();
  9912. viewMatrix.invertToRef(this._worldMatrix);
  9913. return this._worldMatrix;
  9914. };
  9915. Camera.prototype._getViewMatrix = function () {
  9916. return BABYLON.Matrix.Identity();
  9917. };
  9918. Camera.prototype.getViewMatrix = function (force) {
  9919. this._computedViewMatrix = this._computeViewMatrix(force);
  9920. if (!force && this._isSynchronizedViewMatrix()) {
  9921. return this._computedViewMatrix;
  9922. }
  9923. if (!this.parent || !this.parent.getWorldMatrix) {
  9924. this._globalPosition.copyFrom(this.position);
  9925. }
  9926. else {
  9927. if (!this._worldMatrix) {
  9928. this._worldMatrix = BABYLON.Matrix.Identity();
  9929. }
  9930. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9931. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9932. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9933. this._computedViewMatrix.invert();
  9934. this._markSyncedWithParent();
  9935. }
  9936. this._currentRenderId = this.getScene().getRenderId();
  9937. return this._computedViewMatrix;
  9938. };
  9939. Camera.prototype._computeViewMatrix = function (force) {
  9940. if (!force && this._isSynchronizedViewMatrix()) {
  9941. return this._computedViewMatrix;
  9942. }
  9943. this._computedViewMatrix = this._getViewMatrix();
  9944. this._currentRenderId = this.getScene().getRenderId();
  9945. return this._computedViewMatrix;
  9946. };
  9947. Camera.prototype.getProjectionMatrix = function (force) {
  9948. if (!force && this._isSynchronizedProjectionMatrix()) {
  9949. return this._projectionMatrix;
  9950. }
  9951. var engine = this.getEngine();
  9952. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9953. if (this.minZ <= 0) {
  9954. this.minZ = 0.1;
  9955. }
  9956. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9957. return this._projectionMatrix;
  9958. }
  9959. var halfWidth = engine.getRenderWidth() / 2.0;
  9960. var halfHeight = engine.getRenderHeight() / 2.0;
  9961. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9962. return this._projectionMatrix;
  9963. };
  9964. Camera.prototype.dispose = function () {
  9965. // Animations
  9966. this.getScene().stopAnimation(this);
  9967. // Remove from scene
  9968. this.getScene().removeCamera(this);
  9969. while (this._rigCameras.length > 0) {
  9970. this._rigCameras.pop().dispose();
  9971. }
  9972. // Postprocesses
  9973. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9974. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9975. }
  9976. };
  9977. // ---- Camera rigs section ----
  9978. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9979. while (this._rigCameras.length > 0) {
  9980. this._rigCameras.pop().dispose();
  9981. }
  9982. this.cameraRigMode = mode;
  9983. this._cameraRigParams = {};
  9984. switch (this.cameraRigMode) {
  9985. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9986. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9987. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9988. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9989. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9990. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9991. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9992. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9993. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9994. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9995. break;
  9996. }
  9997. var postProcesses = new Array();
  9998. switch (this.cameraRigMode) {
  9999. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10000. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10001. this._rigCameras[0].isIntermediate = true;
  10002. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10003. postProcesses[1].onApply = function (effect) {
  10004. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10005. };
  10006. break;
  10007. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10008. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10009. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10010. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10011. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10012. var secondCamIndex = 1 - firstCamIndex;
  10013. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10014. this._rigCameras[firstCamIndex].isIntermediate = true;
  10015. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10016. break;
  10017. case Camera.RIG_MODE_VR:
  10018. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10019. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10020. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10021. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10022. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10023. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10024. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10025. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10026. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10027. if (metrics.compensateDistortion) {
  10028. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10029. }
  10030. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10031. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10032. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10033. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10034. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10035. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10036. if (metrics.compensateDistortion) {
  10037. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10038. }
  10039. break;
  10040. }
  10041. this._update();
  10042. };
  10043. Camera.prototype._getVRProjectionMatrix = function () {
  10044. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10045. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10046. return this._projectionMatrix;
  10047. };
  10048. Camera.prototype.setCameraRigParameter = function (name, value) {
  10049. this._cameraRigParams[name] = value;
  10050. //provisionnally:
  10051. if (name === "interaxialDistance") {
  10052. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10053. }
  10054. };
  10055. /**
  10056. * May needs to be overridden by children so sub has required properties to be copied
  10057. */
  10058. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10059. return null;
  10060. };
  10061. /**
  10062. * May needs to be overridden by children
  10063. */
  10064. Camera.prototype._updateRigCameras = function () {
  10065. for (var i = 0; i < this._rigCameras.length; i++) {
  10066. this._rigCameras[i].minZ = this.minZ;
  10067. this._rigCameras[i].maxZ = this.maxZ;
  10068. this._rigCameras[i].fov = this.fov;
  10069. }
  10070. // only update viewport when ANAGLYPH
  10071. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10072. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10073. }
  10074. };
  10075. // Statics
  10076. Camera._PERSPECTIVE_CAMERA = 0;
  10077. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10078. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10079. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10080. Camera._RIG_MODE_NONE = 0;
  10081. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10082. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10083. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10084. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10085. Camera._RIG_MODE_VR = 20;
  10086. return Camera;
  10087. })(BABYLON.Node);
  10088. BABYLON.Camera = Camera;
  10089. })(BABYLON || (BABYLON = {}));
  10090. var BABYLON;
  10091. (function (BABYLON) {
  10092. var TargetCamera = (function (_super) {
  10093. __extends(TargetCamera, _super);
  10094. function TargetCamera(name, position, scene) {
  10095. _super.call(this, name, position, scene);
  10096. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10097. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10098. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10099. this.speed = 2.0;
  10100. this.noRotationConstraint = false;
  10101. this.lockedTarget = null;
  10102. this._currentTarget = BABYLON.Vector3.Zero();
  10103. this._viewMatrix = BABYLON.Matrix.Zero();
  10104. this._camMatrix = BABYLON.Matrix.Zero();
  10105. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10106. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10107. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10108. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10109. this._lookAtTemp = BABYLON.Matrix.Zero();
  10110. this._tempMatrix = BABYLON.Matrix.Zero();
  10111. }
  10112. TargetCamera.prototype.getFrontPosition = function (distance) {
  10113. var direction = this.getTarget().subtract(this.position);
  10114. direction.normalize();
  10115. direction.scaleInPlace(distance);
  10116. return this.globalPosition.add(direction);
  10117. };
  10118. TargetCamera.prototype._getLockedTargetPosition = function () {
  10119. if (!this.lockedTarget) {
  10120. return null;
  10121. }
  10122. return this.lockedTarget.position || this.lockedTarget;
  10123. };
  10124. // Cache
  10125. TargetCamera.prototype._initCache = function () {
  10126. _super.prototype._initCache.call(this);
  10127. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10128. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10129. };
  10130. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10131. if (!ignoreParentClass) {
  10132. _super.prototype._updateCache.call(this);
  10133. }
  10134. var lockedTargetPosition = this._getLockedTargetPosition();
  10135. if (!lockedTargetPosition) {
  10136. this._cache.lockedTarget = null;
  10137. }
  10138. else {
  10139. if (!this._cache.lockedTarget) {
  10140. this._cache.lockedTarget = lockedTargetPosition.clone();
  10141. }
  10142. else {
  10143. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10144. }
  10145. }
  10146. this._cache.rotation.copyFrom(this.rotation);
  10147. };
  10148. // Synchronized
  10149. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10150. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10151. return false;
  10152. }
  10153. var lockedTargetPosition = this._getLockedTargetPosition();
  10154. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10155. && this._cache.rotation.equals(this.rotation);
  10156. };
  10157. // Methods
  10158. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10159. var engine = this.getEngine();
  10160. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10161. };
  10162. // Target
  10163. TargetCamera.prototype.setTarget = function (target) {
  10164. this.upVector.normalize();
  10165. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10166. this._camMatrix.invert();
  10167. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10168. var vDir = target.subtract(this.position);
  10169. if (vDir.x >= 0.0) {
  10170. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10171. }
  10172. else {
  10173. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10174. }
  10175. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10176. if (isNaN(this.rotation.x)) {
  10177. this.rotation.x = 0;
  10178. }
  10179. if (isNaN(this.rotation.y)) {
  10180. this.rotation.y = 0;
  10181. }
  10182. if (isNaN(this.rotation.z)) {
  10183. this.rotation.z = 0;
  10184. }
  10185. };
  10186. TargetCamera.prototype.getTarget = function () {
  10187. return this._currentTarget;
  10188. };
  10189. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10190. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10191. };
  10192. TargetCamera.prototype._updatePosition = function () {
  10193. this.position.addInPlace(this.cameraDirection);
  10194. };
  10195. TargetCamera.prototype._checkInputs = function () {
  10196. var needToMove = this._decideIfNeedsToMove();
  10197. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10198. // Move
  10199. if (needToMove) {
  10200. this._updatePosition();
  10201. }
  10202. // Rotate
  10203. if (needToRotate) {
  10204. this.rotation.x += this.cameraRotation.x;
  10205. this.rotation.y += this.cameraRotation.y;
  10206. if (!this.noRotationConstraint) {
  10207. var limit = (Math.PI / 2) * 0.95;
  10208. if (this.rotation.x > limit)
  10209. this.rotation.x = limit;
  10210. if (this.rotation.x < -limit)
  10211. this.rotation.x = -limit;
  10212. }
  10213. }
  10214. // Inertia
  10215. if (needToMove) {
  10216. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10217. this.cameraDirection.x = 0;
  10218. }
  10219. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10220. this.cameraDirection.y = 0;
  10221. }
  10222. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10223. this.cameraDirection.z = 0;
  10224. }
  10225. this.cameraDirection.scaleInPlace(this.inertia);
  10226. }
  10227. if (needToRotate) {
  10228. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10229. this.cameraRotation.x = 0;
  10230. }
  10231. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10232. this.cameraRotation.y = 0;
  10233. }
  10234. this.cameraRotation.scaleInPlace(this.inertia);
  10235. }
  10236. _super.prototype._checkInputs.call(this);
  10237. };
  10238. TargetCamera.prototype._getViewMatrix = function () {
  10239. if (!this.lockedTarget) {
  10240. // Compute
  10241. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10242. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10243. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10244. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10245. this._lookAtTemp.invert();
  10246. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10247. }
  10248. else {
  10249. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10250. }
  10251. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10252. // Computing target and final matrix
  10253. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10254. }
  10255. else {
  10256. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10257. }
  10258. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10259. return this._viewMatrix;
  10260. };
  10261. TargetCamera.prototype._getVRViewMatrix = function () {
  10262. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10263. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10264. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10265. // Computing target and final matrix
  10266. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10267. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10268. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10269. return this._viewMatrix;
  10270. };
  10271. /**
  10272. * @override
  10273. * Override Camera.createRigCamera
  10274. */
  10275. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10276. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10277. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10278. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10279. rigCamera._cameraRigParams = {};
  10280. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10281. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10282. }
  10283. return rigCamera;
  10284. }
  10285. return null;
  10286. };
  10287. /**
  10288. * @override
  10289. * Override Camera._updateRigCameras
  10290. */
  10291. TargetCamera.prototype._updateRigCameras = function () {
  10292. switch (this.cameraRigMode) {
  10293. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10297. case BABYLON.Camera.RIG_MODE_VR:
  10298. var camLeft = this._rigCameras[0];
  10299. var camRight = this._rigCameras[1];
  10300. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10301. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10302. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10303. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10304. camLeft.position.copyFrom(this.position);
  10305. camRight.position.copyFrom(this.position);
  10306. }
  10307. else {
  10308. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10309. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10310. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10311. camLeft.setTarget(this.getTarget());
  10312. camRight.setTarget(this.getTarget());
  10313. }
  10314. break;
  10315. }
  10316. _super.prototype._updateRigCameras.call(this);
  10317. };
  10318. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10319. if (!this._rigCamTransformMatrix) {
  10320. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10321. }
  10322. var target = this.getTarget();
  10323. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10324. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10325. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10326. };
  10327. return TargetCamera;
  10328. })(BABYLON.Camera);
  10329. BABYLON.TargetCamera = TargetCamera;
  10330. })(BABYLON || (BABYLON = {}));
  10331. var BABYLON;
  10332. (function (BABYLON) {
  10333. var FreeCamera = (function (_super) {
  10334. __extends(FreeCamera, _super);
  10335. function FreeCamera(name, position, scene) {
  10336. var _this = this;
  10337. _super.call(this, name, position, scene);
  10338. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10339. this.keysUp = [38];
  10340. this.keysDown = [40];
  10341. this.keysLeft = [37];
  10342. this.keysRight = [39];
  10343. this.checkCollisions = false;
  10344. this.applyGravity = false;
  10345. this.angularSensibility = 2000.0;
  10346. this._keys = [];
  10347. this._collider = new BABYLON.Collider();
  10348. this._needMoveForGravity = false;
  10349. this._oldPosition = BABYLON.Vector3.Zero();
  10350. this._diffPosition = BABYLON.Vector3.Zero();
  10351. this._newPosition = BABYLON.Vector3.Zero();
  10352. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10353. if (collidedMesh === void 0) { collidedMesh = null; }
  10354. //TODO move this to the collision coordinator!
  10355. if (_this.getScene().workerCollisions)
  10356. newPosition.multiplyInPlace(_this._collider.radius);
  10357. var updatePosition = function (newPos) {
  10358. _this._newPosition.copyFrom(newPos);
  10359. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10360. var oldPosition = _this.position.clone();
  10361. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10362. _this.position.addInPlace(_this._diffPosition);
  10363. if (_this.onCollide && collidedMesh) {
  10364. _this.onCollide(collidedMesh);
  10365. }
  10366. }
  10367. };
  10368. updatePosition(newPosition);
  10369. };
  10370. }
  10371. // Controls
  10372. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10373. var _this = this;
  10374. var previousPosition;
  10375. var engine = this.getEngine();
  10376. if (this._attachedElement) {
  10377. return;
  10378. }
  10379. this._attachedElement = element;
  10380. if (this._onMouseDown === undefined) {
  10381. this._onMouseDown = function (evt) {
  10382. previousPosition = {
  10383. x: evt.clientX,
  10384. y: evt.clientY
  10385. };
  10386. if (!noPreventDefault) {
  10387. evt.preventDefault();
  10388. }
  10389. };
  10390. this._onMouseUp = function (evt) {
  10391. previousPosition = null;
  10392. if (!noPreventDefault) {
  10393. evt.preventDefault();
  10394. }
  10395. };
  10396. this._onMouseOut = function (evt) {
  10397. previousPosition = null;
  10398. _this._keys = [];
  10399. if (!noPreventDefault) {
  10400. evt.preventDefault();
  10401. }
  10402. };
  10403. this._onMouseMove = function (evt) {
  10404. if (!previousPosition && !engine.isPointerLock) {
  10405. return;
  10406. }
  10407. var offsetX;
  10408. var offsetY;
  10409. if (!engine.isPointerLock) {
  10410. offsetX = evt.clientX - previousPosition.x;
  10411. offsetY = evt.clientY - previousPosition.y;
  10412. }
  10413. else {
  10414. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10415. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10416. }
  10417. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10418. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10419. previousPosition = {
  10420. x: evt.clientX,
  10421. y: evt.clientY
  10422. };
  10423. if (!noPreventDefault) {
  10424. evt.preventDefault();
  10425. }
  10426. };
  10427. this._onKeyDown = function (evt) {
  10428. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10429. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10430. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10431. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10432. var index = _this._keys.indexOf(evt.keyCode);
  10433. if (index === -1) {
  10434. _this._keys.push(evt.keyCode);
  10435. }
  10436. if (!noPreventDefault) {
  10437. evt.preventDefault();
  10438. }
  10439. }
  10440. };
  10441. this._onKeyUp = function (evt) {
  10442. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10443. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10444. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10445. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10446. var index = _this._keys.indexOf(evt.keyCode);
  10447. if (index >= 0) {
  10448. _this._keys.splice(index, 1);
  10449. }
  10450. if (!noPreventDefault) {
  10451. evt.preventDefault();
  10452. }
  10453. }
  10454. };
  10455. this._onLostFocus = function () {
  10456. _this._keys = [];
  10457. };
  10458. this._reset = function () {
  10459. _this._keys = [];
  10460. previousPosition = null;
  10461. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10462. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10463. };
  10464. }
  10465. element.addEventListener("mousedown", this._onMouseDown, false);
  10466. element.addEventListener("mouseup", this._onMouseUp, false);
  10467. element.addEventListener("mouseout", this._onMouseOut, false);
  10468. element.addEventListener("mousemove", this._onMouseMove, false);
  10469. BABYLON.Tools.RegisterTopRootEvents([
  10470. { name: "keydown", handler: this._onKeyDown },
  10471. { name: "keyup", handler: this._onKeyUp },
  10472. { name: "blur", handler: this._onLostFocus }
  10473. ]);
  10474. };
  10475. FreeCamera.prototype.detachControl = function (element) {
  10476. if (this._attachedElement != element) {
  10477. return;
  10478. }
  10479. element.removeEventListener("mousedown", this._onMouseDown);
  10480. element.removeEventListener("mouseup", this._onMouseUp);
  10481. element.removeEventListener("mouseout", this._onMouseOut);
  10482. element.removeEventListener("mousemove", this._onMouseMove);
  10483. BABYLON.Tools.UnregisterTopRootEvents([
  10484. { name: "keydown", handler: this._onKeyDown },
  10485. { name: "keyup", handler: this._onKeyUp },
  10486. { name: "blur", handler: this._onLostFocus }
  10487. ]);
  10488. this._attachedElement = null;
  10489. if (this._reset) {
  10490. this._reset();
  10491. }
  10492. };
  10493. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10494. var globalPosition;
  10495. if (this.parent) {
  10496. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10497. }
  10498. else {
  10499. globalPosition = this.position;
  10500. }
  10501. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10502. this._collider.radius = this.ellipsoid;
  10503. //no need for clone, as long as gravity is not on.
  10504. var actualVelocity = velocity;
  10505. //add gravity to the velocity to prevent the dual-collision checking
  10506. if (this.applyGravity) {
  10507. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10508. actualVelocity = velocity.add(this.getScene().gravity);
  10509. }
  10510. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10511. };
  10512. FreeCamera.prototype._checkInputs = function () {
  10513. if (!this._localDirection) {
  10514. this._localDirection = BABYLON.Vector3.Zero();
  10515. this._transformedDirection = BABYLON.Vector3.Zero();
  10516. }
  10517. // Keyboard
  10518. for (var index = 0; index < this._keys.length; index++) {
  10519. var keyCode = this._keys[index];
  10520. var speed = this._computeLocalCameraSpeed();
  10521. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10522. this._localDirection.copyFromFloats(-speed, 0, 0);
  10523. }
  10524. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10525. this._localDirection.copyFromFloats(0, 0, speed);
  10526. }
  10527. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10528. this._localDirection.copyFromFloats(speed, 0, 0);
  10529. }
  10530. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10531. this._localDirection.copyFromFloats(0, 0, -speed);
  10532. }
  10533. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10534. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10535. this.cameraDirection.addInPlace(this._transformedDirection);
  10536. }
  10537. _super.prototype._checkInputs.call(this);
  10538. };
  10539. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10540. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10541. };
  10542. FreeCamera.prototype._updatePosition = function () {
  10543. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10544. this._collideWithWorld(this.cameraDirection);
  10545. }
  10546. else {
  10547. this.position.addInPlace(this.cameraDirection);
  10548. }
  10549. };
  10550. return FreeCamera;
  10551. })(BABYLON.TargetCamera);
  10552. BABYLON.FreeCamera = FreeCamera;
  10553. })(BABYLON || (BABYLON = {}));
  10554. var BABYLON;
  10555. (function (BABYLON) {
  10556. var FollowCamera = (function (_super) {
  10557. __extends(FollowCamera, _super);
  10558. function FollowCamera(name, position, scene) {
  10559. _super.call(this, name, position, scene);
  10560. this.radius = 12;
  10561. this.rotationOffset = 0;
  10562. this.heightOffset = 4;
  10563. this.cameraAcceleration = 0.05;
  10564. this.maxCameraSpeed = 20;
  10565. }
  10566. FollowCamera.prototype.getRadians = function (degrees) {
  10567. return degrees * Math.PI / 180;
  10568. };
  10569. FollowCamera.prototype.follow = function (cameraTarget) {
  10570. if (!cameraTarget)
  10571. return;
  10572. var yRotation;
  10573. if (cameraTarget.rotationQuaternion) {
  10574. var rotMatrix = new BABYLON.Matrix();
  10575. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10576. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10577. }
  10578. else {
  10579. yRotation = cameraTarget.rotation.y;
  10580. }
  10581. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10582. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10583. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10584. var dx = targetX - this.position.x;
  10585. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10586. var dz = (targetZ) - this.position.z;
  10587. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10588. var vy = dy * this.cameraAcceleration;
  10589. var vz = dz * this.cameraAcceleration * 2;
  10590. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10591. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10592. }
  10593. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10594. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10595. }
  10596. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10597. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10598. }
  10599. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10600. this.setTarget(cameraTarget.position);
  10601. };
  10602. FollowCamera.prototype._checkInputs = function () {
  10603. _super.prototype._checkInputs.call(this);
  10604. this.follow(this.target);
  10605. };
  10606. return FollowCamera;
  10607. })(BABYLON.TargetCamera);
  10608. BABYLON.FollowCamera = FollowCamera;
  10609. var ArcFollowCamera = (function (_super) {
  10610. __extends(ArcFollowCamera, _super);
  10611. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10612. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10613. this.alpha = alpha;
  10614. this.beta = beta;
  10615. this.radius = radius;
  10616. this.target = target;
  10617. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10618. this.follow();
  10619. }
  10620. ArcFollowCamera.prototype.follow = function () {
  10621. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10622. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10623. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10624. this.position = this.target.position.add(this._cartesianCoordinates);
  10625. this.setTarget(this.target.position);
  10626. };
  10627. ArcFollowCamera.prototype._checkInputs = function () {
  10628. _super.prototype._checkInputs.call(this);
  10629. this.follow();
  10630. };
  10631. return ArcFollowCamera;
  10632. })(BABYLON.TargetCamera);
  10633. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10634. })(BABYLON || (BABYLON = {}));
  10635. var BABYLON;
  10636. (function (BABYLON) {
  10637. // We're mainly based on the logic defined into the FreeCamera code
  10638. var TouchCamera = (function (_super) {
  10639. __extends(TouchCamera, _super);
  10640. function TouchCamera(name, position, scene) {
  10641. _super.call(this, name, position, scene);
  10642. this._offsetX = null;
  10643. this._offsetY = null;
  10644. this._pointerCount = 0;
  10645. this._pointerPressed = [];
  10646. this.angularSensibility = 200000.0;
  10647. this.moveSensibility = 500.0;
  10648. }
  10649. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10650. var _this = this;
  10651. var previousPosition;
  10652. if (this._attachedCanvas) {
  10653. return;
  10654. }
  10655. this._attachedCanvas = canvas;
  10656. if (this._onPointerDown === undefined) {
  10657. this._onPointerDown = function (evt) {
  10658. if (!noPreventDefault) {
  10659. evt.preventDefault();
  10660. }
  10661. _this._pointerPressed.push(evt.pointerId);
  10662. if (_this._pointerPressed.length !== 1) {
  10663. return;
  10664. }
  10665. previousPosition = {
  10666. x: evt.clientX,
  10667. y: evt.clientY
  10668. };
  10669. };
  10670. this._onPointerUp = function (evt) {
  10671. if (!noPreventDefault) {
  10672. evt.preventDefault();
  10673. }
  10674. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10675. if (index === -1) {
  10676. return;
  10677. }
  10678. _this._pointerPressed.splice(index, 1);
  10679. if (index != 0) {
  10680. return;
  10681. }
  10682. previousPosition = null;
  10683. _this._offsetX = null;
  10684. _this._offsetY = null;
  10685. };
  10686. this._onPointerMove = function (evt) {
  10687. if (!noPreventDefault) {
  10688. evt.preventDefault();
  10689. }
  10690. if (!previousPosition) {
  10691. return;
  10692. }
  10693. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10694. if (index != 0) {
  10695. return;
  10696. }
  10697. _this._offsetX = evt.clientX - previousPosition.x;
  10698. _this._offsetY = -(evt.clientY - previousPosition.y);
  10699. };
  10700. this._onLostFocus = function () {
  10701. _this._offsetX = null;
  10702. _this._offsetY = null;
  10703. };
  10704. }
  10705. canvas.addEventListener("pointerdown", this._onPointerDown);
  10706. canvas.addEventListener("pointerup", this._onPointerUp);
  10707. canvas.addEventListener("pointerout", this._onPointerUp);
  10708. canvas.addEventListener("pointermove", this._onPointerMove);
  10709. BABYLON.Tools.RegisterTopRootEvents([
  10710. { name: "blur", handler: this._onLostFocus }
  10711. ]);
  10712. };
  10713. TouchCamera.prototype.detachControl = function (canvas) {
  10714. if (this._attachedCanvas != canvas) {
  10715. return;
  10716. }
  10717. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10718. canvas.removeEventListener("pointerup", this._onPointerUp);
  10719. canvas.removeEventListener("pointerout", this._onPointerUp);
  10720. canvas.removeEventListener("pointermove", this._onPointerMove);
  10721. BABYLON.Tools.UnregisterTopRootEvents([
  10722. { name: "blur", handler: this._onLostFocus }
  10723. ]);
  10724. this._attachedCanvas = null;
  10725. };
  10726. TouchCamera.prototype._checkInputs = function () {
  10727. if (this._offsetX) {
  10728. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10729. if (this._pointerPressed.length > 1) {
  10730. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10731. }
  10732. else {
  10733. var speed = this._computeLocalCameraSpeed();
  10734. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10735. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10736. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10737. }
  10738. }
  10739. _super.prototype._checkInputs.call(this);
  10740. };
  10741. return TouchCamera;
  10742. })(BABYLON.FreeCamera);
  10743. BABYLON.TouchCamera = TouchCamera;
  10744. })(BABYLON || (BABYLON = {}));
  10745. var BABYLON;
  10746. (function (BABYLON) {
  10747. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10748. var ArcRotateCamera = (function (_super) {
  10749. __extends(ArcRotateCamera, _super);
  10750. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10751. var _this = this;
  10752. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10753. this.alpha = alpha;
  10754. this.beta = beta;
  10755. this.radius = radius;
  10756. this.target = target;
  10757. this.inertialAlphaOffset = 0;
  10758. this.inertialBetaOffset = 0;
  10759. this.inertialRadiusOffset = 0;
  10760. this.lowerAlphaLimit = null;
  10761. this.upperAlphaLimit = null;
  10762. this.lowerBetaLimit = 0.01;
  10763. this.upperBetaLimit = Math.PI;
  10764. this.lowerRadiusLimit = null;
  10765. this.upperRadiusLimit = null;
  10766. this.angularSensibilityX = 1000.0;
  10767. this.angularSensibilityY = 1000.0;
  10768. this.wheelPrecision = 3.0;
  10769. this.pinchPrecision = 2.0;
  10770. this.panningSensibility = 50.0;
  10771. this.inertialPanningX = 0;
  10772. this.inertialPanningY = 0;
  10773. this.keysUp = [38];
  10774. this.keysDown = [40];
  10775. this.keysLeft = [37];
  10776. this.keysRight = [39];
  10777. this.zoomOnFactor = 1;
  10778. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10779. this.pinchInwards = true;
  10780. this.allowUpsideDown = true;
  10781. this._keys = [];
  10782. this._viewMatrix = new BABYLON.Matrix();
  10783. this._isRightClick = false;
  10784. this._isCtrlPushed = false;
  10785. this.checkCollisions = false;
  10786. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10787. this._collider = new BABYLON.Collider();
  10788. this._previousPosition = BABYLON.Vector3.Zero();
  10789. this._collisionVelocity = BABYLON.Vector3.Zero();
  10790. this._newPosition = BABYLON.Vector3.Zero();
  10791. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10792. if (collidedMesh === void 0) { collidedMesh = null; }
  10793. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10794. newPosition.multiplyInPlace(_this._collider.radius);
  10795. }
  10796. if (!collidedMesh) {
  10797. _this._previousPosition.copyFrom(_this.position);
  10798. }
  10799. else {
  10800. _this.setPosition(_this.position);
  10801. if (_this.onCollide) {
  10802. _this.onCollide(collidedMesh);
  10803. }
  10804. }
  10805. // Recompute because of constraints
  10806. var cosa = Math.cos(_this.alpha);
  10807. var sina = Math.sin(_this.alpha);
  10808. var cosb = Math.cos(_this.beta);
  10809. var sinb = Math.sin(_this.beta);
  10810. var target = _this._getTargetPosition();
  10811. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10812. _this.position.copyFrom(_this._newPosition);
  10813. var up = _this.upVector;
  10814. if (_this.allowUpsideDown && _this.beta < 0) {
  10815. var up = up.clone();
  10816. up = up.negate();
  10817. }
  10818. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10819. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10820. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10821. _this._collisionTriggered = false;
  10822. };
  10823. if (!this.target) {
  10824. this.target = BABYLON.Vector3.Zero();
  10825. }
  10826. this.getViewMatrix();
  10827. }
  10828. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10829. //deprecated angularSensibility support
  10830. get: function () {
  10831. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10832. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10833. },
  10834. //deprecated angularSensibility support
  10835. set: function (value) {
  10836. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10837. this.angularSensibilityX = value;
  10838. this.angularSensibilityY = value;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. ArcRotateCamera.prototype._getTargetPosition = function () {
  10844. return this.target.position || this.target;
  10845. };
  10846. // Cache
  10847. ArcRotateCamera.prototype._initCache = function () {
  10848. _super.prototype._initCache.call(this);
  10849. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10850. this._cache.alpha = undefined;
  10851. this._cache.beta = undefined;
  10852. this._cache.radius = undefined;
  10853. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10854. };
  10855. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10856. if (!ignoreParentClass) {
  10857. _super.prototype._updateCache.call(this);
  10858. }
  10859. this._cache.target.copyFrom(this._getTargetPosition());
  10860. this._cache.alpha = this.alpha;
  10861. this._cache.beta = this.beta;
  10862. this._cache.radius = this.radius;
  10863. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10864. };
  10865. // Synchronized
  10866. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10867. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10868. return false;
  10869. return this._cache.target.equals(this._getTargetPosition())
  10870. && this._cache.alpha === this.alpha
  10871. && this._cache.beta === this.beta
  10872. && this._cache.radius === this.radius
  10873. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10874. };
  10875. // Methods
  10876. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10877. var _this = this;
  10878. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10879. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10880. var previousPinchDistance = 0;
  10881. var pointers = new BABYLON.SmartCollection();
  10882. if (this._attachedElement) {
  10883. return;
  10884. }
  10885. this._attachedElement = element;
  10886. var engine = this.getEngine();
  10887. if (this._onPointerDown === undefined) {
  10888. this._onPointerDown = function (evt) {
  10889. // Manage panning with right click
  10890. _this._isRightClick = evt.button === 2 ? true : false;
  10891. // manage pointers
  10892. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10893. cacheSoloPointer = pointers.item(evt.pointerId);
  10894. if (!noPreventDefault) {
  10895. evt.preventDefault();
  10896. }
  10897. };
  10898. this._onPointerUp = function (evt) {
  10899. cacheSoloPointer = null;
  10900. previousPinchDistance = 0;
  10901. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10902. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10903. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10904. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10905. pointers.empty();
  10906. if (!noPreventDefault) {
  10907. evt.preventDefault();
  10908. }
  10909. };
  10910. this._onContextMenu = function (evt) {
  10911. evt.preventDefault();
  10912. };
  10913. this._onPointerMove = function (evt) {
  10914. if (!noPreventDefault) {
  10915. evt.preventDefault();
  10916. }
  10917. switch (pointers.count) {
  10918. case 1:
  10919. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10920. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10921. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10922. }
  10923. else {
  10924. var offsetX = evt.clientX - cacheSoloPointer.x;
  10925. var offsetY = evt.clientY - cacheSoloPointer.y;
  10926. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10927. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10928. }
  10929. cacheSoloPointer.x = evt.clientX;
  10930. cacheSoloPointer.y = evt.clientY;
  10931. break;
  10932. case 2:
  10933. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10934. pointers.item(evt.pointerId).x = evt.clientX;
  10935. pointers.item(evt.pointerId).y = evt.clientY;
  10936. var direction = _this.pinchInwards ? 1 : -1;
  10937. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10938. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10939. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10940. if (previousPinchDistance === 0) {
  10941. previousPinchDistance = pinchSquaredDistance;
  10942. return;
  10943. }
  10944. if (pinchSquaredDistance !== previousPinchDistance) {
  10945. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10946. previousPinchDistance = pinchSquaredDistance;
  10947. }
  10948. break;
  10949. default:
  10950. if (pointers.item(evt.pointerId)) {
  10951. pointers.item(evt.pointerId).x = evt.clientX;
  10952. pointers.item(evt.pointerId).y = evt.clientY;
  10953. }
  10954. }
  10955. };
  10956. this._onMouseMove = function (evt) {
  10957. if (!engine.isPointerLock) {
  10958. return;
  10959. }
  10960. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10961. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10962. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10963. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10964. if (!noPreventDefault) {
  10965. evt.preventDefault();
  10966. }
  10967. };
  10968. this._wheel = function (event) {
  10969. var delta = 0;
  10970. if (event.wheelDelta) {
  10971. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10972. }
  10973. else if (event.detail) {
  10974. delta = -event.detail / _this.wheelPrecision;
  10975. }
  10976. if (delta)
  10977. _this.inertialRadiusOffset += delta;
  10978. if (event.preventDefault) {
  10979. if (!noPreventDefault) {
  10980. event.preventDefault();
  10981. }
  10982. }
  10983. };
  10984. this._onKeyDown = function (evt) {
  10985. _this._isCtrlPushed = evt.ctrlKey;
  10986. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10987. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10988. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10989. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10990. var index = _this._keys.indexOf(evt.keyCode);
  10991. if (index === -1) {
  10992. _this._keys.push(evt.keyCode);
  10993. }
  10994. if (evt.preventDefault) {
  10995. if (!noPreventDefault) {
  10996. evt.preventDefault();
  10997. }
  10998. }
  10999. }
  11000. };
  11001. this._onKeyUp = function (evt) {
  11002. _this._isCtrlPushed = evt.ctrlKey;
  11003. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11004. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11005. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11006. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11007. var index = _this._keys.indexOf(evt.keyCode);
  11008. if (index >= 0) {
  11009. _this._keys.splice(index, 1);
  11010. }
  11011. if (evt.preventDefault) {
  11012. if (!noPreventDefault) {
  11013. evt.preventDefault();
  11014. }
  11015. }
  11016. }
  11017. };
  11018. this._onLostFocus = function () {
  11019. _this._keys = [];
  11020. pointers.empty();
  11021. previousPinchDistance = 0;
  11022. cacheSoloPointer = null;
  11023. };
  11024. this._onGestureStart = function (e) {
  11025. if (window.MSGesture === undefined) {
  11026. return;
  11027. }
  11028. if (!_this._MSGestureHandler) {
  11029. _this._MSGestureHandler = new MSGesture();
  11030. _this._MSGestureHandler.target = element;
  11031. }
  11032. _this._MSGestureHandler.addPointer(e.pointerId);
  11033. };
  11034. this._onGesture = function (e) {
  11035. _this.radius *= e.scale;
  11036. if (e.preventDefault) {
  11037. if (!noPreventDefault) {
  11038. e.stopPropagation();
  11039. e.preventDefault();
  11040. }
  11041. }
  11042. };
  11043. this._reset = function () {
  11044. _this._keys = [];
  11045. _this.inertialAlphaOffset = 0;
  11046. _this.inertialBetaOffset = 0;
  11047. _this.inertialRadiusOffset = 0;
  11048. pointers.empty();
  11049. previousPinchDistance = 0;
  11050. cacheSoloPointer = null;
  11051. };
  11052. }
  11053. if (!useCtrlForPanning) {
  11054. element.addEventListener("contextmenu", this._onContextMenu, false);
  11055. }
  11056. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11057. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11058. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11059. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11060. element.addEventListener("mousemove", this._onMouseMove, false);
  11061. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11062. element.addEventListener("MSGestureChange", this._onGesture, false);
  11063. element.addEventListener('mousewheel', this._wheel, false);
  11064. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11065. BABYLON.Tools.RegisterTopRootEvents([
  11066. { name: "keydown", handler: this._onKeyDown },
  11067. { name: "keyup", handler: this._onKeyUp },
  11068. { name: "blur", handler: this._onLostFocus }
  11069. ]);
  11070. };
  11071. ArcRotateCamera.prototype.detachControl = function (element) {
  11072. if (this._attachedElement !== element) {
  11073. return;
  11074. }
  11075. element.removeEventListener("contextmenu", this._onContextMenu);
  11076. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11077. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11078. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11079. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11080. element.removeEventListener("mousemove", this._onMouseMove);
  11081. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11082. element.removeEventListener("MSGestureChange", this._onGesture);
  11083. element.removeEventListener('mousewheel', this._wheel);
  11084. element.removeEventListener('DOMMouseScroll', this._wheel);
  11085. BABYLON.Tools.UnregisterTopRootEvents([
  11086. { name: "keydown", handler: this._onKeyDown },
  11087. { name: "keyup", handler: this._onKeyUp },
  11088. { name: "blur", handler: this._onLostFocus }
  11089. ]);
  11090. this._MSGestureHandler = null;
  11091. this._attachedElement = null;
  11092. if (this._reset) {
  11093. this._reset();
  11094. }
  11095. };
  11096. ArcRotateCamera.prototype._checkInputs = function () {
  11097. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11098. if (this._collisionTriggered) {
  11099. return;
  11100. }
  11101. // Keyboard
  11102. for (var index = 0; index < this._keys.length; index++) {
  11103. var keyCode = this._keys[index];
  11104. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11105. this.inertialAlphaOffset -= 0.01;
  11106. }
  11107. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11108. this.inertialBetaOffset -= 0.01;
  11109. }
  11110. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11111. this.inertialAlphaOffset += 0.01;
  11112. }
  11113. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11114. this.inertialBetaOffset += 0.01;
  11115. }
  11116. }
  11117. // Inertia
  11118. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11119. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11120. this.beta += this.inertialBetaOffset;
  11121. this.radius -= this.inertialRadiusOffset;
  11122. this.inertialAlphaOffset *= this.inertia;
  11123. this.inertialBetaOffset *= this.inertia;
  11124. this.inertialRadiusOffset *= this.inertia;
  11125. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11126. this.inertialAlphaOffset = 0;
  11127. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11128. this.inertialBetaOffset = 0;
  11129. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11130. this.inertialRadiusOffset = 0;
  11131. }
  11132. // Panning inertia
  11133. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11134. if (!this._localDirection) {
  11135. this._localDirection = BABYLON.Vector3.Zero();
  11136. this._transformedDirection = BABYLON.Vector3.Zero();
  11137. }
  11138. this.inertialPanningX *= this.inertia;
  11139. this.inertialPanningY *= this.inertia;
  11140. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11141. this.inertialPanningX = 0;
  11142. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11143. this.inertialPanningY = 0;
  11144. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11145. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11146. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11147. this.target.addInPlace(this._transformedDirection);
  11148. }
  11149. // Limits
  11150. this._checkLimits();
  11151. _super.prototype._checkInputs.call(this);
  11152. };
  11153. ArcRotateCamera.prototype._checkLimits = function () {
  11154. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11155. if (this.allowUpsideDown && this.beta > Math.PI) {
  11156. this.beta = this.beta - (2 * Math.PI);
  11157. }
  11158. }
  11159. else {
  11160. if (this.beta < this.lowerBetaLimit) {
  11161. this.beta = this.lowerBetaLimit;
  11162. }
  11163. }
  11164. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11165. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11166. this.beta = this.beta + (2 * Math.PI);
  11167. }
  11168. }
  11169. else {
  11170. if (this.beta > this.upperBetaLimit) {
  11171. this.beta = this.upperBetaLimit;
  11172. }
  11173. }
  11174. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11175. this.alpha = this.lowerAlphaLimit;
  11176. }
  11177. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11178. this.alpha = this.upperAlphaLimit;
  11179. }
  11180. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11181. this.radius = this.lowerRadiusLimit;
  11182. }
  11183. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11184. this.radius = this.upperRadiusLimit;
  11185. }
  11186. };
  11187. ArcRotateCamera.prototype.setPosition = function (position) {
  11188. if (this.position.equals(position)) {
  11189. return;
  11190. }
  11191. var radiusv3 = position.subtract(this._getTargetPosition());
  11192. this.radius = radiusv3.length();
  11193. // Alpha
  11194. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11195. if (radiusv3.z < 0) {
  11196. this.alpha = 2 * Math.PI - this.alpha;
  11197. }
  11198. // Beta
  11199. this.beta = Math.acos(radiusv3.y / this.radius);
  11200. this._checkLimits();
  11201. };
  11202. ArcRotateCamera.prototype.setTarget = function (target) {
  11203. this.target = target;
  11204. };
  11205. ArcRotateCamera.prototype._getViewMatrix = function () {
  11206. // Compute
  11207. var cosa = Math.cos(this.alpha);
  11208. var sina = Math.sin(this.alpha);
  11209. var cosb = Math.cos(this.beta);
  11210. var sinb = Math.sin(this.beta);
  11211. var target = this._getTargetPosition();
  11212. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11213. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11214. this._collider.radius = this.collisionRadius;
  11215. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11216. this._collisionTriggered = true;
  11217. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11218. }
  11219. else {
  11220. this.position.copyFrom(this._newPosition);
  11221. var up = this.upVector;
  11222. if (this.allowUpsideDown && this.beta < 0) {
  11223. var up = up.clone();
  11224. up = up.negate();
  11225. }
  11226. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11227. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11228. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11229. }
  11230. return this._viewMatrix;
  11231. };
  11232. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11233. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11234. meshes = meshes || this.getScene().meshes;
  11235. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11236. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11237. this.radius = distance * this.zoomOnFactor;
  11238. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11239. };
  11240. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11241. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11242. var meshesOrMinMaxVector;
  11243. var distance;
  11244. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11245. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11246. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11247. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11248. }
  11249. else {
  11250. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11251. distance = meshesOrMinMaxVectorAndDistance.distance;
  11252. }
  11253. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11254. if (!doNotUpdateMaxZ) {
  11255. this.maxZ = distance * 2;
  11256. }
  11257. };
  11258. /**
  11259. * @override
  11260. * Override Camera.createRigCamera
  11261. */
  11262. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11263. switch (this.cameraRigMode) {
  11264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11266. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11267. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11268. case BABYLON.Camera.RIG_MODE_VR:
  11269. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11270. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11271. }
  11272. };
  11273. /**
  11274. * @override
  11275. * Override Camera._updateRigCameras
  11276. */
  11277. ArcRotateCamera.prototype._updateRigCameras = function () {
  11278. switch (this.cameraRigMode) {
  11279. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11283. case BABYLON.Camera.RIG_MODE_VR:
  11284. var camLeft = this._rigCameras[0];
  11285. var camRight = this._rigCameras[1];
  11286. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11287. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11288. camLeft.beta = camRight.beta = this.beta;
  11289. camLeft.radius = camRight.radius = this.radius;
  11290. break;
  11291. }
  11292. _super.prototype._updateRigCameras.call(this);
  11293. };
  11294. return ArcRotateCamera;
  11295. })(BABYLON.TargetCamera);
  11296. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11297. })(BABYLON || (BABYLON = {}));
  11298. var BABYLON;
  11299. (function (BABYLON) {
  11300. var RenderingManager = (function () {
  11301. function RenderingManager(scene) {
  11302. this._renderingGroups = new Array();
  11303. this._scene = scene;
  11304. }
  11305. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11306. if (this._scene._activeParticleSystems.length === 0) {
  11307. return;
  11308. }
  11309. // Particles
  11310. var activeCamera = this._scene.activeCamera;
  11311. var beforeParticlesDate = BABYLON.Tools.Now;
  11312. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11313. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11314. if (particleSystem.renderingGroupId !== index) {
  11315. continue;
  11316. }
  11317. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11318. continue;
  11319. }
  11320. this._clearDepthBuffer();
  11321. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11322. this._scene._activeParticles += particleSystem.render();
  11323. }
  11324. }
  11325. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11326. };
  11327. RenderingManager.prototype._renderSprites = function (index) {
  11328. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11329. return;
  11330. }
  11331. // Sprites
  11332. var activeCamera = this._scene.activeCamera;
  11333. var beforeSpritessDate = BABYLON.Tools.Now;
  11334. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11335. var spriteManager = this._scene.spriteManagers[id];
  11336. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11337. this._clearDepthBuffer();
  11338. spriteManager.render();
  11339. }
  11340. }
  11341. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11342. };
  11343. RenderingManager.prototype._clearDepthBuffer = function () {
  11344. if (this._depthBufferAlreadyCleaned) {
  11345. return;
  11346. }
  11347. this._scene.getEngine().clear(0, false, true);
  11348. this._depthBufferAlreadyCleaned = true;
  11349. };
  11350. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11351. if (this._currentRenderSprites) {
  11352. this._renderSprites(this._currentIndex);
  11353. }
  11354. if (this._currentRenderParticles) {
  11355. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11356. }
  11357. };
  11358. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11359. this._currentActiveMeshes = activeMeshes;
  11360. this._currentRenderParticles = renderParticles;
  11361. this._currentRenderSprites = renderSprites;
  11362. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11363. this._depthBufferAlreadyCleaned = false;
  11364. var renderingGroup = this._renderingGroups[index];
  11365. var needToStepBack = false;
  11366. this._currentIndex = index;
  11367. if (renderingGroup) {
  11368. this._clearDepthBuffer();
  11369. if (!renderingGroup.onBeforeTransparentRendering) {
  11370. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11371. }
  11372. if (!renderingGroup.render(customRenderFunction)) {
  11373. this._renderingGroups.splice(index, 1);
  11374. needToStepBack = true;
  11375. this._renderSpritesAndParticles();
  11376. }
  11377. }
  11378. else {
  11379. this._renderSpritesAndParticles();
  11380. }
  11381. if (needToStepBack) {
  11382. index--;
  11383. }
  11384. }
  11385. };
  11386. RenderingManager.prototype.reset = function () {
  11387. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11388. if (renderingGroup) {
  11389. renderingGroup.prepare();
  11390. }
  11391. });
  11392. };
  11393. RenderingManager.prototype.dispatch = function (subMesh) {
  11394. var mesh = subMesh.getMesh();
  11395. var renderingGroupId = mesh.renderingGroupId || 0;
  11396. if (!this._renderingGroups[renderingGroupId]) {
  11397. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11398. }
  11399. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11400. };
  11401. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11402. return RenderingManager;
  11403. })();
  11404. BABYLON.RenderingManager = RenderingManager;
  11405. })(BABYLON || (BABYLON = {}));
  11406. var BABYLON;
  11407. (function (BABYLON) {
  11408. var RenderingGroup = (function () {
  11409. function RenderingGroup(index, scene) {
  11410. this.index = index;
  11411. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11412. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11413. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11414. this._scene = scene;
  11415. }
  11416. RenderingGroup.prototype.render = function (customRenderFunction) {
  11417. if (customRenderFunction) {
  11418. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11419. return true;
  11420. }
  11421. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11422. if (this.onBeforeTransparentRendering) {
  11423. this.onBeforeTransparentRendering();
  11424. }
  11425. return false;
  11426. }
  11427. var engine = this._scene.getEngine();
  11428. // Opaque
  11429. var subIndex;
  11430. var submesh;
  11431. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11432. submesh = this._opaqueSubMeshes.data[subIndex];
  11433. submesh.render(false);
  11434. }
  11435. // Alpha test
  11436. engine.setAlphaTesting(true);
  11437. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11438. submesh = this._alphaTestSubMeshes.data[subIndex];
  11439. submesh.render(false);
  11440. }
  11441. engine.setAlphaTesting(false);
  11442. if (this.onBeforeTransparentRendering) {
  11443. this.onBeforeTransparentRendering();
  11444. }
  11445. // Transparent
  11446. if (this._transparentSubMeshes.length) {
  11447. // Sorting
  11448. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11449. submesh = this._transparentSubMeshes.data[subIndex];
  11450. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11451. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11452. }
  11453. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11454. sortedArray.sort(function (a, b) {
  11455. // Alpha index first
  11456. if (a._alphaIndex > b._alphaIndex) {
  11457. return 1;
  11458. }
  11459. if (a._alphaIndex < b._alphaIndex) {
  11460. return -1;
  11461. }
  11462. // Then distance to camera
  11463. if (a._distanceToCamera < b._distanceToCamera) {
  11464. return 1;
  11465. }
  11466. if (a._distanceToCamera > b._distanceToCamera) {
  11467. return -1;
  11468. }
  11469. return 0;
  11470. });
  11471. // Rendering
  11472. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11473. submesh = sortedArray[subIndex];
  11474. submesh.render(true);
  11475. }
  11476. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11477. }
  11478. return true;
  11479. };
  11480. RenderingGroup.prototype.prepare = function () {
  11481. this._opaqueSubMeshes.reset();
  11482. this._transparentSubMeshes.reset();
  11483. this._alphaTestSubMeshes.reset();
  11484. };
  11485. RenderingGroup.prototype.dispatch = function (subMesh) {
  11486. var material = subMesh.getMaterial();
  11487. var mesh = subMesh.getMesh();
  11488. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11489. this._transparentSubMeshes.push(subMesh);
  11490. }
  11491. else if (material.needAlphaTesting()) {
  11492. this._alphaTestSubMeshes.push(subMesh);
  11493. }
  11494. else {
  11495. this._opaqueSubMeshes.push(subMesh); // Opaque
  11496. }
  11497. };
  11498. return RenderingGroup;
  11499. })();
  11500. BABYLON.RenderingGroup = RenderingGroup;
  11501. })(BABYLON || (BABYLON = {}));
  11502. var BABYLON;
  11503. (function (BABYLON) {
  11504. /**
  11505. * Represents a scene to be rendered by the engine.
  11506. * @see http://doc.babylonjs.com/page.php?p=21911
  11507. */
  11508. var Scene = (function () {
  11509. /**
  11510. * @constructor
  11511. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11512. */
  11513. function Scene(engine) {
  11514. // Members
  11515. this.autoClear = true;
  11516. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11517. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11518. this.forceWireframe = false;
  11519. this.forcePointsCloud = false;
  11520. this.forceShowBoundingBoxes = false;
  11521. this.animationsEnabled = true;
  11522. this.constantlyUpdateMeshUnderPointer = false;
  11523. 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
  11524. // Fog
  11525. /**
  11526. * is fog enabled on this scene.
  11527. * @type {boolean}
  11528. */
  11529. this.fogEnabled = true;
  11530. this.fogMode = Scene.FOGMODE_NONE;
  11531. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11532. this.fogDensity = 0.1;
  11533. this.fogStart = 0;
  11534. this.fogEnd = 1000.0;
  11535. // Lights
  11536. /**
  11537. * is shadow enabled on this scene.
  11538. * @type {boolean}
  11539. */
  11540. this.shadowsEnabled = true;
  11541. /**
  11542. * is light enabled on this scene.
  11543. * @type {boolean}
  11544. */
  11545. this.lightsEnabled = true;
  11546. /**
  11547. * All of the lights added to this scene.
  11548. * @see BABYLON.Light
  11549. * @type {BABYLON.Light[]}
  11550. */
  11551. this.lights = new Array();
  11552. // Cameras
  11553. /**
  11554. * All of the cameras added to this scene.
  11555. * @see BABYLON.Camera
  11556. * @type {BABYLON.Camera[]}
  11557. */
  11558. this.cameras = new Array();
  11559. this.activeCameras = new Array();
  11560. // Meshes
  11561. /**
  11562. * All of the (abstract) meshes added to this scene.
  11563. * @see BABYLON.AbstractMesh
  11564. * @type {BABYLON.AbstractMesh[]}
  11565. */
  11566. this.meshes = new Array();
  11567. // Geometries
  11568. this._geometries = new Array();
  11569. this.materials = new Array();
  11570. this.multiMaterials = new Array();
  11571. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11572. // Textures
  11573. this.texturesEnabled = true;
  11574. this.textures = new Array();
  11575. // Particles
  11576. this.particlesEnabled = true;
  11577. this.particleSystems = new Array();
  11578. // Sprites
  11579. this.spritesEnabled = true;
  11580. this.spriteManagers = new Array();
  11581. // Layers
  11582. this.layers = new Array();
  11583. // Skeletons
  11584. this.skeletonsEnabled = true;
  11585. this.skeletons = new Array();
  11586. // Lens flares
  11587. this.lensFlaresEnabled = true;
  11588. this.lensFlareSystems = new Array();
  11589. // Collisions
  11590. this.collisionsEnabled = true;
  11591. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11592. // Postprocesses
  11593. this.postProcessesEnabled = true;
  11594. // Customs render targets
  11595. this.renderTargetsEnabled = true;
  11596. this.dumpNextRenderTargets = false;
  11597. this.customRenderTargets = new Array();
  11598. // Imported meshes
  11599. this.importedMeshesFiles = new Array();
  11600. // Probes
  11601. this.probesEnabled = true;
  11602. this.reflectionProbes = new Array();
  11603. this._actionManagers = new Array();
  11604. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11605. // Procedural textures
  11606. this.proceduralTexturesEnabled = true;
  11607. this._proceduralTextures = new Array();
  11608. this.soundTracks = new Array();
  11609. this._audioEnabled = true;
  11610. this._headphone = false;
  11611. this._totalVertices = 0;
  11612. this._activeIndices = 0;
  11613. this._activeParticles = 0;
  11614. this._lastFrameDuration = 0;
  11615. this._evaluateActiveMeshesDuration = 0;
  11616. this._renderTargetsDuration = 0;
  11617. this._particlesDuration = 0;
  11618. this._renderDuration = 0;
  11619. this._spritesDuration = 0;
  11620. this._animationRatio = 0;
  11621. this._renderId = 0;
  11622. this._executeWhenReadyTimeoutId = -1;
  11623. this._toBeDisposed = new BABYLON.SmartArray(256);
  11624. this._onReadyCallbacks = new Array();
  11625. this._pendingData = []; //ANY
  11626. this._onBeforeRenderCallbacks = new Array();
  11627. this._onAfterRenderCallbacks = new Array();
  11628. this._activeMeshes = new BABYLON.SmartArray(256);
  11629. this._processedMaterials = new BABYLON.SmartArray(256);
  11630. this._renderTargets = new BABYLON.SmartArray(256);
  11631. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11632. this._activeSkeletons = new BABYLON.SmartArray(32);
  11633. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11634. this._activeBones = 0;
  11635. this._activeAnimatables = new Array();
  11636. this._transformMatrix = BABYLON.Matrix.Zero();
  11637. this._edgesRenderers = new BABYLON.SmartArray(16);
  11638. this._uniqueIdCounter = 0;
  11639. this._engine = engine;
  11640. engine.scenes.push(this);
  11641. this._renderingManager = new BABYLON.RenderingManager(this);
  11642. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11643. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11644. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11645. if (BABYLON.OutlineRenderer) {
  11646. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11647. }
  11648. this.attachControl();
  11649. this._debugLayer = new BABYLON.DebugLayer(this);
  11650. if (BABYLON.SoundTrack) {
  11651. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11652. }
  11653. //simplification queue
  11654. if (BABYLON.SimplificationQueue) {
  11655. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11656. }
  11657. //collision coordinator initialization. For now legacy per default.
  11658. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11659. }
  11660. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11661. get: function () {
  11662. return Scene._FOGMODE_NONE;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11668. get: function () {
  11669. return Scene._FOGMODE_EXP;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11675. get: function () {
  11676. return Scene._FOGMODE_EXP2;
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11682. get: function () {
  11683. return Scene._FOGMODE_LINEAR;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Scene.prototype, "debugLayer", {
  11689. // Properties
  11690. get: function () {
  11691. return this._debugLayer;
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11697. get: function () {
  11698. return this._workerCollisions;
  11699. },
  11700. set: function (enabled) {
  11701. enabled = (enabled && !!Worker);
  11702. this._workerCollisions = enabled;
  11703. if (this.collisionCoordinator) {
  11704. this.collisionCoordinator.destroy();
  11705. }
  11706. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11707. this.collisionCoordinator.init(this);
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11713. get: function () {
  11714. return this._selectionOctree;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11720. /**
  11721. * The mesh that is currently under the pointer.
  11722. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11723. */
  11724. get: function () {
  11725. return this._meshUnderPointer;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Scene.prototype, "pointerX", {
  11731. /**
  11732. * Current on-screen X position of the pointer
  11733. * @return {number} X position of the pointer
  11734. */
  11735. get: function () {
  11736. return this._pointerX;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Scene.prototype, "pointerY", {
  11742. /**
  11743. * Current on-screen Y position of the pointer
  11744. * @return {number} Y position of the pointer
  11745. */
  11746. get: function () {
  11747. return this._pointerY;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Scene.prototype.getCachedMaterial = function () {
  11753. return this._cachedMaterial;
  11754. };
  11755. Scene.prototype.getBoundingBoxRenderer = function () {
  11756. return this._boundingBoxRenderer;
  11757. };
  11758. Scene.prototype.getOutlineRenderer = function () {
  11759. return this._outlineRenderer;
  11760. };
  11761. Scene.prototype.getEngine = function () {
  11762. return this._engine;
  11763. };
  11764. Scene.prototype.getTotalVertices = function () {
  11765. return this._totalVertices;
  11766. };
  11767. Scene.prototype.getActiveIndices = function () {
  11768. return this._activeIndices;
  11769. };
  11770. Scene.prototype.getActiveParticles = function () {
  11771. return this._activeParticles;
  11772. };
  11773. Scene.prototype.getActiveBones = function () {
  11774. return this._activeBones;
  11775. };
  11776. // Stats
  11777. Scene.prototype.getLastFrameDuration = function () {
  11778. return this._lastFrameDuration;
  11779. };
  11780. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11781. return this._evaluateActiveMeshesDuration;
  11782. };
  11783. Scene.prototype.getActiveMeshes = function () {
  11784. return this._activeMeshes;
  11785. };
  11786. Scene.prototype.getRenderTargetsDuration = function () {
  11787. return this._renderTargetsDuration;
  11788. };
  11789. Scene.prototype.getRenderDuration = function () {
  11790. return this._renderDuration;
  11791. };
  11792. Scene.prototype.getParticlesDuration = function () {
  11793. return this._particlesDuration;
  11794. };
  11795. Scene.prototype.getSpritesDuration = function () {
  11796. return this._spritesDuration;
  11797. };
  11798. Scene.prototype.getAnimationRatio = function () {
  11799. return this._animationRatio;
  11800. };
  11801. Scene.prototype.getRenderId = function () {
  11802. return this._renderId;
  11803. };
  11804. Scene.prototype.incrementRenderId = function () {
  11805. this._renderId++;
  11806. };
  11807. Scene.prototype._updatePointerPosition = function (evt) {
  11808. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11809. this._pointerX = evt.clientX - canvasRect.left;
  11810. this._pointerY = evt.clientY - canvasRect.top;
  11811. if (this.cameraToUseForPointers) {
  11812. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11813. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11814. }
  11815. };
  11816. // Pointers handling
  11817. Scene.prototype.attachControl = function () {
  11818. var _this = this;
  11819. var spritePredicate = function (sprite) {
  11820. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11821. };
  11822. this._onPointerMove = function (evt) {
  11823. var canvas = _this._engine.getRenderingCanvas();
  11824. _this._updatePointerPosition(evt);
  11825. // Meshes
  11826. 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);
  11827. if (pickResult.hit && pickResult.pickedMesh) {
  11828. _this._meshUnderPointer = pickResult.pickedMesh;
  11829. _this.setPointerOverMesh(pickResult.pickedMesh);
  11830. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11831. canvas.style.cursor = "pointer";
  11832. }
  11833. else {
  11834. canvas.style.cursor = "";
  11835. }
  11836. }
  11837. else {
  11838. // Sprites
  11839. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11840. if (pickResult.hit && pickResult.pickedSprite) {
  11841. canvas.style.cursor = "pointer";
  11842. return;
  11843. }
  11844. // Restore pointer
  11845. _this.setPointerOverMesh(null);
  11846. canvas.style.cursor = "";
  11847. _this._meshUnderPointer = null;
  11848. }
  11849. };
  11850. this._onPointerDown = function (evt) {
  11851. _this._updatePointerPosition(evt);
  11852. var predicate = null;
  11853. // Meshes
  11854. if (!_this.onPointerDown) {
  11855. predicate = function (mesh) {
  11856. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11857. };
  11858. }
  11859. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11860. if (pickResult.hit && pickResult.pickedMesh) {
  11861. if (pickResult.pickedMesh.actionManager) {
  11862. switch (evt.button) {
  11863. case 0:
  11864. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11865. break;
  11866. case 1:
  11867. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11868. break;
  11869. case 2:
  11870. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11871. break;
  11872. }
  11873. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11874. }
  11875. }
  11876. if (_this.onPointerDown) {
  11877. _this.onPointerDown(evt, pickResult);
  11878. }
  11879. // Sprites
  11880. if (_this.spriteManagers.length > 0) {
  11881. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11882. if (pickResult.hit && pickResult.pickedSprite) {
  11883. if (pickResult.pickedSprite.actionManager) {
  11884. switch (evt.button) {
  11885. case 0:
  11886. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11887. break;
  11888. case 1:
  11889. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11890. break;
  11891. case 2:
  11892. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11893. break;
  11894. }
  11895. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11896. }
  11897. }
  11898. }
  11899. };
  11900. this._onPointerUp = function (evt) {
  11901. var predicate = null;
  11902. _this._updatePointerPosition(evt);
  11903. if (!_this.onPointerUp) {
  11904. predicate = function (mesh) {
  11905. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11906. };
  11907. }
  11908. // Meshes
  11909. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11910. if (pickResult.hit && pickResult.pickedMesh) {
  11911. if (pickResult.pickedMesh.actionManager) {
  11912. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11913. }
  11914. }
  11915. if (_this.onPointerUp) {
  11916. _this.onPointerUp(evt, pickResult);
  11917. }
  11918. // Sprites
  11919. if (_this.spriteManagers.length > 0) {
  11920. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11921. if (pickResult.hit && pickResult.pickedSprite) {
  11922. if (pickResult.pickedSprite.actionManager) {
  11923. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11924. }
  11925. }
  11926. }
  11927. };
  11928. this._onKeyDown = function (evt) {
  11929. if (_this.actionManager) {
  11930. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11931. }
  11932. };
  11933. this._onKeyUp = function (evt) {
  11934. if (_this.actionManager) {
  11935. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11936. }
  11937. };
  11938. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11939. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11940. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11941. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11942. // Wheel
  11943. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11944. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11945. BABYLON.Tools.RegisterTopRootEvents([
  11946. { name: "keydown", handler: this._onKeyDown },
  11947. { name: "keyup", handler: this._onKeyUp }
  11948. ]);
  11949. };
  11950. Scene.prototype.detachControl = function () {
  11951. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11952. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11953. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11954. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11955. // Wheel
  11956. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11957. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11958. BABYLON.Tools.UnregisterTopRootEvents([
  11959. { name: "keydown", handler: this._onKeyDown },
  11960. { name: "keyup", handler: this._onKeyUp }
  11961. ]);
  11962. };
  11963. // Ready
  11964. Scene.prototype.isReady = function () {
  11965. if (this._pendingData.length > 0) {
  11966. return false;
  11967. }
  11968. var index;
  11969. for (index = 0; index < this._geometries.length; index++) {
  11970. var geometry = this._geometries[index];
  11971. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11972. return false;
  11973. }
  11974. }
  11975. for (index = 0; index < this.meshes.length; index++) {
  11976. var mesh = this.meshes[index];
  11977. if (!mesh.isReady()) {
  11978. return false;
  11979. }
  11980. var mat = mesh.material;
  11981. if (mat) {
  11982. if (!mat.isReady(mesh)) {
  11983. return false;
  11984. }
  11985. }
  11986. }
  11987. return true;
  11988. };
  11989. Scene.prototype.resetCachedMaterial = function () {
  11990. this._cachedMaterial = null;
  11991. };
  11992. Scene.prototype.registerBeforeRender = function (func) {
  11993. this._onBeforeRenderCallbacks.push(func);
  11994. };
  11995. Scene.prototype.unregisterBeforeRender = function (func) {
  11996. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11997. if (index > -1) {
  11998. this._onBeforeRenderCallbacks.splice(index, 1);
  11999. }
  12000. };
  12001. Scene.prototype.registerAfterRender = function (func) {
  12002. this._onAfterRenderCallbacks.push(func);
  12003. };
  12004. Scene.prototype.unregisterAfterRender = function (func) {
  12005. var index = this._onAfterRenderCallbacks.indexOf(func);
  12006. if (index > -1) {
  12007. this._onAfterRenderCallbacks.splice(index, 1);
  12008. }
  12009. };
  12010. Scene.prototype._addPendingData = function (data) {
  12011. this._pendingData.push(data);
  12012. };
  12013. Scene.prototype._removePendingData = function (data) {
  12014. var index = this._pendingData.indexOf(data);
  12015. if (index !== -1) {
  12016. this._pendingData.splice(index, 1);
  12017. }
  12018. };
  12019. Scene.prototype.getWaitingItemsCount = function () {
  12020. return this._pendingData.length;
  12021. };
  12022. /**
  12023. * Registers a function to be executed when the scene is ready.
  12024. * @param {Function} func - the function to be executed.
  12025. */
  12026. Scene.prototype.executeWhenReady = function (func) {
  12027. var _this = this;
  12028. this._onReadyCallbacks.push(func);
  12029. if (this._executeWhenReadyTimeoutId !== -1) {
  12030. return;
  12031. }
  12032. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12033. _this._checkIsReady();
  12034. }, 150);
  12035. };
  12036. Scene.prototype._checkIsReady = function () {
  12037. var _this = this;
  12038. if (this.isReady()) {
  12039. this._onReadyCallbacks.forEach(function (func) {
  12040. func();
  12041. });
  12042. this._onReadyCallbacks = [];
  12043. this._executeWhenReadyTimeoutId = -1;
  12044. return;
  12045. }
  12046. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12047. _this._checkIsReady();
  12048. }, 150);
  12049. };
  12050. // Animations
  12051. /**
  12052. * Will start the animation sequence of a given target
  12053. * @param target - the target
  12054. * @param {number} from - from which frame should animation start
  12055. * @param {number} to - till which frame should animation run.
  12056. * @param {boolean} [loop] - should the animation loop
  12057. * @param {number} [speedRatio] - the speed in which to run the animation
  12058. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12059. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12060. * @return {BABYLON.Animatable} the animatable object created for this animation
  12061. * @see BABYLON.Animatable
  12062. * @see http://doc.babylonjs.com/page.php?p=22081
  12063. */
  12064. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12065. if (speedRatio === void 0) { speedRatio = 1.0; }
  12066. this.stopAnimation(target);
  12067. if (!animatable) {
  12068. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12069. }
  12070. // Local animations
  12071. if (target.animations) {
  12072. animatable.appendAnimations(target, target.animations);
  12073. }
  12074. // Children animations
  12075. if (target.getAnimatables) {
  12076. var animatables = target.getAnimatables();
  12077. for (var index = 0; index < animatables.length; index++) {
  12078. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12079. }
  12080. }
  12081. return animatable;
  12082. };
  12083. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12084. if (speedRatio === undefined) {
  12085. speedRatio = 1.0;
  12086. }
  12087. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12088. return animatable;
  12089. };
  12090. Scene.prototype.getAnimatableByTarget = function (target) {
  12091. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12092. if (this._activeAnimatables[index].target === target) {
  12093. return this._activeAnimatables[index];
  12094. }
  12095. }
  12096. return null;
  12097. };
  12098. /**
  12099. * Will stop the animation of the given target
  12100. * @param target - the target
  12101. * @see beginAnimation
  12102. */
  12103. Scene.prototype.stopAnimation = function (target) {
  12104. var animatable = this.getAnimatableByTarget(target);
  12105. if (animatable) {
  12106. animatable.stop();
  12107. }
  12108. };
  12109. Scene.prototype._animate = function () {
  12110. if (!this.animationsEnabled) {
  12111. return;
  12112. }
  12113. if (!this._animationStartDate) {
  12114. this._animationStartDate = BABYLON.Tools.Now;
  12115. }
  12116. // Getting time
  12117. var now = BABYLON.Tools.Now;
  12118. var delay = now - this._animationStartDate;
  12119. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12120. this._activeAnimatables[index]._animate(delay);
  12121. }
  12122. };
  12123. // Matrix
  12124. Scene.prototype.getViewMatrix = function () {
  12125. return this._viewMatrix;
  12126. };
  12127. Scene.prototype.getProjectionMatrix = function () {
  12128. return this._projectionMatrix;
  12129. };
  12130. Scene.prototype.getTransformMatrix = function () {
  12131. return this._transformMatrix;
  12132. };
  12133. Scene.prototype.setTransformMatrix = function (view, projection) {
  12134. this._viewMatrix = view;
  12135. this._projectionMatrix = projection;
  12136. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12137. };
  12138. // Methods
  12139. Scene.prototype.addMesh = function (newMesh) {
  12140. newMesh.uniqueId = this._uniqueIdCounter++;
  12141. var position = this.meshes.push(newMesh);
  12142. //notify the collision coordinator
  12143. this.collisionCoordinator.onMeshAdded(newMesh);
  12144. if (this.onNewMeshAdded) {
  12145. this.onNewMeshAdded(newMesh, position, this);
  12146. }
  12147. };
  12148. Scene.prototype.removeMesh = function (toRemove) {
  12149. var index = this.meshes.indexOf(toRemove);
  12150. if (index !== -1) {
  12151. // Remove from the scene if mesh found
  12152. this.meshes.splice(index, 1);
  12153. }
  12154. //notify the collision coordinator
  12155. this.collisionCoordinator.onMeshRemoved(toRemove);
  12156. if (this.onMeshRemoved) {
  12157. this.onMeshRemoved(toRemove);
  12158. }
  12159. return index;
  12160. };
  12161. Scene.prototype.removeSkeleton = function (toRemove) {
  12162. var index = this.skeletons.indexOf(toRemove);
  12163. if (index !== -1) {
  12164. // Remove from the scene if mesh found
  12165. this.skeletons.splice(index, 1);
  12166. }
  12167. return index;
  12168. };
  12169. Scene.prototype.removeLight = function (toRemove) {
  12170. var index = this.lights.indexOf(toRemove);
  12171. if (index !== -1) {
  12172. // Remove from the scene if mesh found
  12173. this.lights.splice(index, 1);
  12174. }
  12175. if (this.onLightRemoved) {
  12176. this.onLightRemoved(toRemove);
  12177. }
  12178. return index;
  12179. };
  12180. Scene.prototype.removeCamera = function (toRemove) {
  12181. var index = this.cameras.indexOf(toRemove);
  12182. if (index !== -1) {
  12183. // Remove from the scene if mesh found
  12184. this.cameras.splice(index, 1);
  12185. }
  12186. // Remove from activeCameras
  12187. var index2 = this.activeCameras.indexOf(toRemove);
  12188. if (index2 !== -1) {
  12189. // Remove from the scene if mesh found
  12190. this.activeCameras.splice(index2, 1);
  12191. }
  12192. // Reset the activeCamera
  12193. if (this.activeCamera === toRemove) {
  12194. if (this.cameras.length > 0) {
  12195. this.activeCamera = this.cameras[0];
  12196. }
  12197. else {
  12198. this.activeCamera = null;
  12199. }
  12200. }
  12201. if (this.onCameraRemoved) {
  12202. this.onCameraRemoved(toRemove);
  12203. }
  12204. return index;
  12205. };
  12206. Scene.prototype.addLight = function (newLight) {
  12207. newLight.uniqueId = this._uniqueIdCounter++;
  12208. var position = this.lights.push(newLight);
  12209. if (this.onNewLightAdded) {
  12210. this.onNewLightAdded(newLight, position, this);
  12211. }
  12212. };
  12213. Scene.prototype.addCamera = function (newCamera) {
  12214. newCamera.uniqueId = this._uniqueIdCounter++;
  12215. var position = this.cameras.push(newCamera);
  12216. if (this.onNewCameraAdded) {
  12217. this.onNewCameraAdded(newCamera, position, this);
  12218. }
  12219. };
  12220. /**
  12221. * sets the active camera of the scene using its ID
  12222. * @param {string} id - the camera's ID
  12223. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12224. * @see activeCamera
  12225. */
  12226. Scene.prototype.setActiveCameraByID = function (id) {
  12227. var camera = this.getCameraByID(id);
  12228. if (camera) {
  12229. this.activeCamera = camera;
  12230. return camera;
  12231. }
  12232. return null;
  12233. };
  12234. /**
  12235. * sets the active camera of the scene using its name
  12236. * @param {string} name - the camera's name
  12237. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12238. * @see activeCamera
  12239. */
  12240. Scene.prototype.setActiveCameraByName = function (name) {
  12241. var camera = this.getCameraByName(name);
  12242. if (camera) {
  12243. this.activeCamera = camera;
  12244. return camera;
  12245. }
  12246. return null;
  12247. };
  12248. /**
  12249. * get a material using its id
  12250. * @param {string} the material's ID
  12251. * @return {BABYLON.Material|null} the material or null if none found.
  12252. */
  12253. Scene.prototype.getMaterialByID = function (id) {
  12254. for (var index = 0; index < this.materials.length; index++) {
  12255. if (this.materials[index].id === id) {
  12256. return this.materials[index];
  12257. }
  12258. }
  12259. return null;
  12260. };
  12261. /**
  12262. * get a material using its name
  12263. * @param {string} the material's name
  12264. * @return {BABYLON.Material|null} the material or null if none found.
  12265. */
  12266. Scene.prototype.getMaterialByName = function (name) {
  12267. for (var index = 0; index < this.materials.length; index++) {
  12268. if (this.materials[index].name === name) {
  12269. return this.materials[index];
  12270. }
  12271. }
  12272. return null;
  12273. };
  12274. Scene.prototype.getLensFlareSystemByName = function (name) {
  12275. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12276. if (this.lensFlareSystems[index].name === name) {
  12277. return this.lensFlareSystems[index];
  12278. }
  12279. }
  12280. return null;
  12281. };
  12282. Scene.prototype.getCameraByID = function (id) {
  12283. for (var index = 0; index < this.cameras.length; index++) {
  12284. if (this.cameras[index].id === id) {
  12285. return this.cameras[index];
  12286. }
  12287. }
  12288. return null;
  12289. };
  12290. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12291. for (var index = 0; index < this.cameras.length; index++) {
  12292. if (this.cameras[index].uniqueId === uniqueId) {
  12293. return this.cameras[index];
  12294. }
  12295. }
  12296. return null;
  12297. };
  12298. /**
  12299. * get a camera using its name
  12300. * @param {string} the camera's name
  12301. * @return {BABYLON.Camera|null} the camera or null if none found.
  12302. */
  12303. Scene.prototype.getCameraByName = function (name) {
  12304. for (var index = 0; index < this.cameras.length; index++) {
  12305. if (this.cameras[index].name === name) {
  12306. return this.cameras[index];
  12307. }
  12308. }
  12309. return null;
  12310. };
  12311. /**
  12312. * get a light node using its name
  12313. * @param {string} the light's name
  12314. * @return {BABYLON.Light|null} the light or null if none found.
  12315. */
  12316. Scene.prototype.getLightByName = function (name) {
  12317. for (var index = 0; index < this.lights.length; index++) {
  12318. if (this.lights[index].name === name) {
  12319. return this.lights[index];
  12320. }
  12321. }
  12322. return null;
  12323. };
  12324. /**
  12325. * get a light node using its ID
  12326. * @param {string} the light's id
  12327. * @return {BABYLON.Light|null} the light or null if none found.
  12328. */
  12329. Scene.prototype.getLightByID = function (id) {
  12330. for (var index = 0; index < this.lights.length; index++) {
  12331. if (this.lights[index].id === id) {
  12332. return this.lights[index];
  12333. }
  12334. }
  12335. return null;
  12336. };
  12337. /**
  12338. * get a light node using its scene-generated unique ID
  12339. * @param {number} the light's unique id
  12340. * @return {BABYLON.Light|null} the light or null if none found.
  12341. */
  12342. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12343. for (var index = 0; index < this.lights.length; index++) {
  12344. if (this.lights[index].uniqueId === uniqueId) {
  12345. return this.lights[index];
  12346. }
  12347. }
  12348. return null;
  12349. };
  12350. /**
  12351. * get a geometry using its ID
  12352. * @param {string} the geometry's id
  12353. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12354. */
  12355. Scene.prototype.getGeometryByID = function (id) {
  12356. for (var index = 0; index < this._geometries.length; index++) {
  12357. if (this._geometries[index].id === id) {
  12358. return this._geometries[index];
  12359. }
  12360. }
  12361. return null;
  12362. };
  12363. /**
  12364. * add a new geometry to this scene.
  12365. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12366. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12367. * @return {boolean} was the geometry added or not
  12368. */
  12369. Scene.prototype.pushGeometry = function (geometry, force) {
  12370. if (!force && this.getGeometryByID(geometry.id)) {
  12371. return false;
  12372. }
  12373. this._geometries.push(geometry);
  12374. //notify the collision coordinator
  12375. this.collisionCoordinator.onGeometryAdded(geometry);
  12376. if (this.onGeometryAdded) {
  12377. this.onGeometryAdded(geometry);
  12378. }
  12379. return true;
  12380. };
  12381. /**
  12382. * Removes an existing geometry
  12383. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12384. * @return {boolean} was the geometry removed or not
  12385. */
  12386. Scene.prototype.removeGeometry = function (geometry) {
  12387. var index = this._geometries.indexOf(geometry);
  12388. if (index > -1) {
  12389. this._geometries.splice(index, 1);
  12390. //notify the collision coordinator
  12391. this.collisionCoordinator.onGeometryDeleted(geometry);
  12392. if (this.onGeometryRemoved) {
  12393. this.onGeometryRemoved(geometry);
  12394. }
  12395. return true;
  12396. }
  12397. return false;
  12398. };
  12399. Scene.prototype.getGeometries = function () {
  12400. return this._geometries;
  12401. };
  12402. /**
  12403. * Get the first added mesh found of a given ID
  12404. * @param {string} id - the id to search for
  12405. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12406. */
  12407. Scene.prototype.getMeshByID = function (id) {
  12408. for (var index = 0; index < this.meshes.length; index++) {
  12409. if (this.meshes[index].id === id) {
  12410. return this.meshes[index];
  12411. }
  12412. }
  12413. return null;
  12414. };
  12415. /**
  12416. * Get a mesh with its auto-generated unique id
  12417. * @param {number} uniqueId - the unique id to search for
  12418. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12419. */
  12420. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12421. for (var index = 0; index < this.meshes.length; index++) {
  12422. if (this.meshes[index].uniqueId === uniqueId) {
  12423. return this.meshes[index];
  12424. }
  12425. }
  12426. return null;
  12427. };
  12428. /**
  12429. * Get a the last added mesh found of a given ID
  12430. * @param {string} id - the id to search for
  12431. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12432. */
  12433. Scene.prototype.getLastMeshByID = function (id) {
  12434. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12435. if (this.meshes[index].id === id) {
  12436. return this.meshes[index];
  12437. }
  12438. }
  12439. return null;
  12440. };
  12441. /**
  12442. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12443. * @param {string} id - the id to search for
  12444. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12445. */
  12446. Scene.prototype.getLastEntryByID = function (id) {
  12447. var index;
  12448. for (index = this.meshes.length - 1; index >= 0; index--) {
  12449. if (this.meshes[index].id === id) {
  12450. return this.meshes[index];
  12451. }
  12452. }
  12453. for (index = this.cameras.length - 1; index >= 0; index--) {
  12454. if (this.cameras[index].id === id) {
  12455. return this.cameras[index];
  12456. }
  12457. }
  12458. for (index = this.lights.length - 1; index >= 0; index--) {
  12459. if (this.lights[index].id === id) {
  12460. return this.lights[index];
  12461. }
  12462. }
  12463. return null;
  12464. };
  12465. Scene.prototype.getNodeByID = function (id) {
  12466. var mesh = this.getMeshByID(id);
  12467. if (mesh) {
  12468. return mesh;
  12469. }
  12470. var light = this.getLightByID(id);
  12471. if (light) {
  12472. return light;
  12473. }
  12474. return this.getCameraByID(id);
  12475. };
  12476. Scene.prototype.getNodeByName = function (name) {
  12477. var mesh = this.getMeshByName(name);
  12478. if (mesh) {
  12479. return mesh;
  12480. }
  12481. var light = this.getLightByName(name);
  12482. if (light) {
  12483. return light;
  12484. }
  12485. return this.getCameraByName(name);
  12486. };
  12487. Scene.prototype.getMeshByName = function (name) {
  12488. for (var index = 0; index < this.meshes.length; index++) {
  12489. if (this.meshes[index].name === name) {
  12490. return this.meshes[index];
  12491. }
  12492. }
  12493. return null;
  12494. };
  12495. Scene.prototype.getSoundByName = function (name) {
  12496. var index;
  12497. if (BABYLON.AudioEngine) {
  12498. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12499. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12500. return this.mainSoundTrack.soundCollection[index];
  12501. }
  12502. }
  12503. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12504. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12505. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12506. return this.soundTracks[sdIndex].soundCollection[index];
  12507. }
  12508. }
  12509. }
  12510. }
  12511. return null;
  12512. };
  12513. Scene.prototype.getLastSkeletonByID = function (id) {
  12514. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12515. if (this.skeletons[index].id === id) {
  12516. return this.skeletons[index];
  12517. }
  12518. }
  12519. return null;
  12520. };
  12521. Scene.prototype.getSkeletonById = function (id) {
  12522. for (var index = 0; index < this.skeletons.length; index++) {
  12523. if (this.skeletons[index].id === id) {
  12524. return this.skeletons[index];
  12525. }
  12526. }
  12527. return null;
  12528. };
  12529. Scene.prototype.getSkeletonByName = function (name) {
  12530. for (var index = 0; index < this.skeletons.length; index++) {
  12531. if (this.skeletons[index].name === name) {
  12532. return this.skeletons[index];
  12533. }
  12534. }
  12535. return null;
  12536. };
  12537. Scene.prototype.isActiveMesh = function (mesh) {
  12538. return (this._activeMeshes.indexOf(mesh) !== -1);
  12539. };
  12540. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12541. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12542. var material = subMesh.getMaterial();
  12543. if (mesh.showSubMeshesBoundingBox) {
  12544. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12545. }
  12546. if (material) {
  12547. // Render targets
  12548. if (material.getRenderTargetTextures) {
  12549. if (this._processedMaterials.indexOf(material) === -1) {
  12550. this._processedMaterials.push(material);
  12551. this._renderTargets.concat(material.getRenderTargetTextures());
  12552. }
  12553. }
  12554. // Dispatch
  12555. this._activeIndices += subMesh.indexCount;
  12556. this._renderingManager.dispatch(subMesh);
  12557. }
  12558. }
  12559. };
  12560. Scene.prototype._evaluateActiveMeshes = function () {
  12561. this.activeCamera._activeMeshes.reset();
  12562. this._activeMeshes.reset();
  12563. this._renderingManager.reset();
  12564. this._processedMaterials.reset();
  12565. this._activeParticleSystems.reset();
  12566. this._activeSkeletons.reset();
  12567. this._softwareSkinnedMeshes.reset();
  12568. this._boundingBoxRenderer.reset();
  12569. this._edgesRenderers.reset();
  12570. if (!this._frustumPlanes) {
  12571. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12572. }
  12573. else {
  12574. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12575. }
  12576. // Meshes
  12577. var meshes;
  12578. var len;
  12579. if (this._selectionOctree) {
  12580. var selection = this._selectionOctree.select(this._frustumPlanes);
  12581. meshes = selection.data;
  12582. len = selection.length;
  12583. }
  12584. else {
  12585. len = this.meshes.length;
  12586. meshes = this.meshes;
  12587. }
  12588. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12589. var mesh = meshes[meshIndex];
  12590. if (mesh.isBlocked) {
  12591. continue;
  12592. }
  12593. this._totalVertices += mesh.getTotalVertices();
  12594. if (!mesh.isReady() || !mesh.isEnabled()) {
  12595. continue;
  12596. }
  12597. mesh.computeWorldMatrix();
  12598. // Intersections
  12599. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12600. this._meshesForIntersections.pushNoDuplicate(mesh);
  12601. }
  12602. // Switch to current LOD
  12603. var meshLOD = mesh.getLOD(this.activeCamera);
  12604. if (!meshLOD) {
  12605. continue;
  12606. }
  12607. mesh._preActivate();
  12608. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12609. this._activeMeshes.push(mesh);
  12610. this.activeCamera._activeMeshes.push(mesh);
  12611. mesh._activate(this._renderId);
  12612. this._activeMesh(meshLOD);
  12613. }
  12614. }
  12615. // Particle systems
  12616. var beforeParticlesDate = BABYLON.Tools.Now;
  12617. if (this.particlesEnabled) {
  12618. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12619. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12620. var particleSystem = this.particleSystems[particleIndex];
  12621. if (!particleSystem.isStarted()) {
  12622. continue;
  12623. }
  12624. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12625. this._activeParticleSystems.push(particleSystem);
  12626. particleSystem.animate();
  12627. }
  12628. }
  12629. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12630. }
  12631. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12632. };
  12633. Scene.prototype._activeMesh = function (mesh) {
  12634. if (mesh.skeleton && this.skeletonsEnabled) {
  12635. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12636. if (!mesh.computeBonesUsingShaders) {
  12637. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12638. }
  12639. }
  12640. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12641. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12642. }
  12643. if (mesh._edgesRenderer) {
  12644. this._edgesRenderers.push(mesh._edgesRenderer);
  12645. }
  12646. if (mesh && mesh.subMeshes) {
  12647. // Submeshes Octrees
  12648. var len;
  12649. var subMeshes;
  12650. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12651. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12652. len = intersections.length;
  12653. subMeshes = intersections.data;
  12654. }
  12655. else {
  12656. subMeshes = mesh.subMeshes;
  12657. len = subMeshes.length;
  12658. }
  12659. for (var subIndex = 0; subIndex < len; subIndex++) {
  12660. var subMesh = subMeshes[subIndex];
  12661. this._evaluateSubMesh(subMesh, mesh);
  12662. }
  12663. }
  12664. };
  12665. Scene.prototype.updateTransformMatrix = function (force) {
  12666. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12667. };
  12668. Scene.prototype._renderForCamera = function (camera) {
  12669. var engine = this._engine;
  12670. this.activeCamera = camera;
  12671. if (!this.activeCamera)
  12672. throw new Error("Active camera not set");
  12673. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12674. // Viewport
  12675. engine.setViewport(this.activeCamera.viewport);
  12676. // Camera
  12677. this.resetCachedMaterial();
  12678. this._renderId++;
  12679. this.updateTransformMatrix();
  12680. if (this.beforeCameraRender) {
  12681. this.beforeCameraRender(this.activeCamera);
  12682. }
  12683. // Meshes
  12684. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12685. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12686. this._evaluateActiveMeshes();
  12687. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12688. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12689. // Skeletons
  12690. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12691. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12692. skeleton.prepare();
  12693. }
  12694. // Software skinning
  12695. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12696. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12697. mesh.applySkeleton(mesh.skeleton);
  12698. }
  12699. // Render targets
  12700. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12701. if (this.renderTargetsEnabled) {
  12702. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12703. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12704. var renderTarget = this._renderTargets.data[renderIndex];
  12705. if (renderTarget._shouldRender()) {
  12706. this._renderId++;
  12707. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12708. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12709. }
  12710. }
  12711. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12712. this._renderId++;
  12713. }
  12714. if (this._renderTargets.length > 0) {
  12715. engine.restoreDefaultFramebuffer();
  12716. }
  12717. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12718. // Prepare Frame
  12719. this.postProcessManager._prepareFrame();
  12720. var beforeRenderDate = BABYLON.Tools.Now;
  12721. // Backgrounds
  12722. var layerIndex;
  12723. var layer;
  12724. if (this.layers.length) {
  12725. engine.setDepthBuffer(false);
  12726. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12727. layer = this.layers[layerIndex];
  12728. if (layer.isBackground) {
  12729. layer.render();
  12730. }
  12731. }
  12732. engine.setDepthBuffer(true);
  12733. }
  12734. // Render
  12735. BABYLON.Tools.StartPerformanceCounter("Main render");
  12736. this._renderingManager.render(null, null, true, true);
  12737. BABYLON.Tools.EndPerformanceCounter("Main render");
  12738. // Bounding boxes
  12739. this._boundingBoxRenderer.render();
  12740. // Edges
  12741. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12742. this._edgesRenderers.data[edgesRendererIndex].render();
  12743. }
  12744. // Lens flares
  12745. if (this.lensFlaresEnabled) {
  12746. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12747. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12748. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12749. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12750. lensFlareSystem.render();
  12751. }
  12752. }
  12753. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12754. }
  12755. // Foregrounds
  12756. if (this.layers.length) {
  12757. engine.setDepthBuffer(false);
  12758. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12759. layer = this.layers[layerIndex];
  12760. if (!layer.isBackground) {
  12761. layer.render();
  12762. }
  12763. }
  12764. engine.setDepthBuffer(true);
  12765. }
  12766. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12767. // Finalize frame
  12768. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12769. // Update camera
  12770. this.activeCamera._updateFromScene();
  12771. // Reset some special arrays
  12772. this._renderTargets.reset();
  12773. if (this.afterCameraRender) {
  12774. this.afterCameraRender(this.activeCamera);
  12775. }
  12776. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12777. };
  12778. Scene.prototype._processSubCameras = function (camera) {
  12779. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12780. this._renderForCamera(camera);
  12781. return;
  12782. }
  12783. // rig cameras
  12784. for (var index = 0; index < camera._rigCameras.length; index++) {
  12785. this._renderForCamera(camera._rigCameras[index]);
  12786. }
  12787. this.activeCamera = camera;
  12788. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12789. // Update camera
  12790. this.activeCamera._updateFromScene();
  12791. };
  12792. Scene.prototype._checkIntersections = function () {
  12793. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12794. var sourceMesh = this._meshesForIntersections.data[index];
  12795. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12796. var action = sourceMesh.actionManager.actions[actionIndex];
  12797. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12798. var parameters = action.getTriggerParameter();
  12799. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12800. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12801. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12802. if (areIntersecting && currentIntersectionInProgress === -1) {
  12803. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12804. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12805. sourceMesh._intersectionsInProgress.push(otherMesh);
  12806. }
  12807. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12808. sourceMesh._intersectionsInProgress.push(otherMesh);
  12809. }
  12810. }
  12811. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12812. //They intersected, and now they don't.
  12813. //is this trigger an exit trigger? execute an event.
  12814. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12815. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12816. }
  12817. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12818. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12819. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12820. }
  12821. }
  12822. }
  12823. }
  12824. }
  12825. };
  12826. Scene.prototype.render = function () {
  12827. var startDate = BABYLON.Tools.Now;
  12828. this._particlesDuration = 0;
  12829. this._spritesDuration = 0;
  12830. this._activeParticles = 0;
  12831. this._renderDuration = 0;
  12832. this._renderTargetsDuration = 0;
  12833. this._evaluateActiveMeshesDuration = 0;
  12834. this._totalVertices = 0;
  12835. this._activeIndices = 0;
  12836. this._activeBones = 0;
  12837. this.getEngine().resetDrawCalls();
  12838. this._meshesForIntersections.reset();
  12839. this.resetCachedMaterial();
  12840. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12841. // Actions
  12842. if (this.actionManager) {
  12843. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12844. }
  12845. //Simplification Queue
  12846. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12847. this.simplificationQueue.executeNext();
  12848. }
  12849. // Animations
  12850. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12851. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12852. this._animate();
  12853. // Physics
  12854. if (this._physicsEngine) {
  12855. BABYLON.Tools.StartPerformanceCounter("Physics");
  12856. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12857. BABYLON.Tools.EndPerformanceCounter("Physics");
  12858. }
  12859. // Before render
  12860. if (this.beforeRender) {
  12861. this.beforeRender();
  12862. }
  12863. var callbackIndex;
  12864. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12865. this._onBeforeRenderCallbacks[callbackIndex]();
  12866. }
  12867. // Customs render targets
  12868. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12869. var engine = this.getEngine();
  12870. var currentActiveCamera = this.activeCamera;
  12871. if (this.renderTargetsEnabled) {
  12872. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12873. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12874. var renderTarget = this.customRenderTargets[customIndex];
  12875. if (renderTarget._shouldRender()) {
  12876. this._renderId++;
  12877. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12878. if (!this.activeCamera)
  12879. throw new Error("Active camera not set");
  12880. // Viewport
  12881. engine.setViewport(this.activeCamera.viewport);
  12882. // Camera
  12883. this.updateTransformMatrix();
  12884. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12885. }
  12886. }
  12887. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12888. this._renderId++;
  12889. }
  12890. if (this.customRenderTargets.length > 0) {
  12891. engine.restoreDefaultFramebuffer();
  12892. }
  12893. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12894. this.activeCamera = currentActiveCamera;
  12895. // Procedural textures
  12896. if (this.proceduralTexturesEnabled) {
  12897. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12898. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12899. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12900. if (proceduralTexture._shouldRender()) {
  12901. proceduralTexture.render();
  12902. }
  12903. }
  12904. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12905. }
  12906. // Clear
  12907. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12908. // Shadows
  12909. if (this.shadowsEnabled) {
  12910. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12911. var light = this.lights[lightIndex];
  12912. var shadowGenerator = light.getShadowGenerator();
  12913. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12914. this._renderTargets.push(shadowGenerator.getShadowMap());
  12915. }
  12916. }
  12917. }
  12918. // Depth renderer
  12919. if (this._depthRenderer) {
  12920. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12921. }
  12922. // RenderPipeline
  12923. this.postProcessRenderPipelineManager.update();
  12924. // Multi-cameras?
  12925. if (this.activeCameras.length > 0) {
  12926. var currentRenderId = this._renderId;
  12927. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12928. this._renderId = currentRenderId;
  12929. this._processSubCameras(this.activeCameras[cameraIndex]);
  12930. }
  12931. }
  12932. else {
  12933. if (!this.activeCamera) {
  12934. throw new Error("No camera defined");
  12935. }
  12936. this._processSubCameras(this.activeCamera);
  12937. }
  12938. // Intersection checks
  12939. this._checkIntersections();
  12940. // Update the audio listener attached to the camera
  12941. if (BABYLON.AudioEngine) {
  12942. this._updateAudioParameters();
  12943. }
  12944. // After render
  12945. if (this.afterRender) {
  12946. this.afterRender();
  12947. }
  12948. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12949. this._onAfterRenderCallbacks[callbackIndex]();
  12950. }
  12951. // Cleaning
  12952. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12953. this._toBeDisposed.data[index].dispose();
  12954. this._toBeDisposed[index] = null;
  12955. }
  12956. this._toBeDisposed.reset();
  12957. if (this.dumpNextRenderTargets) {
  12958. this.dumpNextRenderTargets = false;
  12959. }
  12960. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12961. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12962. };
  12963. Scene.prototype._updateAudioParameters = function () {
  12964. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12965. return;
  12966. }
  12967. var listeningCamera;
  12968. var audioEngine = BABYLON.Engine.audioEngine;
  12969. if (this.activeCameras.length > 0) {
  12970. listeningCamera = this.activeCameras[0];
  12971. }
  12972. else {
  12973. listeningCamera = this.activeCamera;
  12974. }
  12975. if (listeningCamera && audioEngine.canUseWebAudio) {
  12976. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12977. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12978. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12979. cameraDirection.normalize();
  12980. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12981. var i;
  12982. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12983. var sound = this.mainSoundTrack.soundCollection[i];
  12984. if (sound.useCustomAttenuation) {
  12985. sound.updateDistanceFromListener();
  12986. }
  12987. }
  12988. for (i = 0; i < this.soundTracks.length; i++) {
  12989. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12990. sound = this.soundTracks[i].soundCollection[j];
  12991. if (sound.useCustomAttenuation) {
  12992. sound.updateDistanceFromListener();
  12993. }
  12994. }
  12995. }
  12996. }
  12997. };
  12998. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12999. // Audio
  13000. get: function () {
  13001. return this._audioEnabled;
  13002. },
  13003. set: function (value) {
  13004. this._audioEnabled = value;
  13005. if (BABYLON.AudioEngine) {
  13006. if (this._audioEnabled) {
  13007. this._enableAudio();
  13008. }
  13009. else {
  13010. this._disableAudio();
  13011. }
  13012. }
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Scene.prototype._disableAudio = function () {
  13018. var i;
  13019. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13020. this.mainSoundTrack.soundCollection[i].pause();
  13021. }
  13022. for (i = 0; i < this.soundTracks.length; i++) {
  13023. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13024. this.soundTracks[i].soundCollection[j].pause();
  13025. }
  13026. }
  13027. };
  13028. Scene.prototype._enableAudio = function () {
  13029. var i;
  13030. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13031. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13032. this.mainSoundTrack.soundCollection[i].play();
  13033. }
  13034. }
  13035. for (i = 0; i < this.soundTracks.length; i++) {
  13036. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13037. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13038. this.soundTracks[i].soundCollection[j].play();
  13039. }
  13040. }
  13041. }
  13042. };
  13043. Object.defineProperty(Scene.prototype, "headphone", {
  13044. get: function () {
  13045. return this._headphone;
  13046. },
  13047. set: function (value) {
  13048. this._headphone = value;
  13049. if (BABYLON.AudioEngine) {
  13050. if (this._headphone) {
  13051. this._switchAudioModeForHeadphones();
  13052. }
  13053. else {
  13054. this._switchAudioModeForNormalSpeakers();
  13055. }
  13056. }
  13057. },
  13058. enumerable: true,
  13059. configurable: true
  13060. });
  13061. Scene.prototype._switchAudioModeForHeadphones = function () {
  13062. this.mainSoundTrack.switchPanningModelToHRTF();
  13063. for (var i = 0; i < this.soundTracks.length; i++) {
  13064. this.soundTracks[i].switchPanningModelToHRTF();
  13065. }
  13066. };
  13067. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13068. this.mainSoundTrack.switchPanningModelToEqualPower();
  13069. for (var i = 0; i < this.soundTracks.length; i++) {
  13070. this.soundTracks[i].switchPanningModelToEqualPower();
  13071. }
  13072. };
  13073. Scene.prototype.enableDepthRenderer = function () {
  13074. if (this._depthRenderer) {
  13075. return this._depthRenderer;
  13076. }
  13077. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13078. return this._depthRenderer;
  13079. };
  13080. Scene.prototype.disableDepthRenderer = function () {
  13081. if (!this._depthRenderer) {
  13082. return;
  13083. }
  13084. this._depthRenderer.dispose();
  13085. this._depthRenderer = null;
  13086. };
  13087. Scene.prototype.dispose = function () {
  13088. this.beforeRender = null;
  13089. this.afterRender = null;
  13090. this.skeletons = [];
  13091. this._boundingBoxRenderer.dispose();
  13092. if (this._depthRenderer) {
  13093. this._depthRenderer.dispose();
  13094. }
  13095. // Debug layer
  13096. this.debugLayer.hide();
  13097. // Events
  13098. if (this.onDispose) {
  13099. this.onDispose();
  13100. }
  13101. this._onBeforeRenderCallbacks = [];
  13102. this._onAfterRenderCallbacks = [];
  13103. this.detachControl();
  13104. // Release sounds & sounds tracks
  13105. if (BABYLON.AudioEngine) {
  13106. this.disposeSounds();
  13107. }
  13108. // Detach cameras
  13109. var canvas = this._engine.getRenderingCanvas();
  13110. var index;
  13111. for (index = 0; index < this.cameras.length; index++) {
  13112. this.cameras[index].detachControl(canvas);
  13113. }
  13114. // Release lights
  13115. while (this.lights.length) {
  13116. this.lights[0].dispose();
  13117. }
  13118. // Release meshes
  13119. while (this.meshes.length) {
  13120. this.meshes[0].dispose(true);
  13121. }
  13122. // Release cameras
  13123. while (this.cameras.length) {
  13124. this.cameras[0].dispose();
  13125. }
  13126. // Release materials
  13127. while (this.materials.length) {
  13128. this.materials[0].dispose();
  13129. }
  13130. // Release particles
  13131. while (this.particleSystems.length) {
  13132. this.particleSystems[0].dispose();
  13133. }
  13134. // Release sprites
  13135. while (this.spriteManagers.length) {
  13136. this.spriteManagers[0].dispose();
  13137. }
  13138. // Release layers
  13139. while (this.layers.length) {
  13140. this.layers[0].dispose();
  13141. }
  13142. // Release textures
  13143. while (this.textures.length) {
  13144. this.textures[0].dispose();
  13145. }
  13146. // Post-processes
  13147. this.postProcessManager.dispose();
  13148. // Physics
  13149. if (this._physicsEngine) {
  13150. this.disablePhysicsEngine();
  13151. }
  13152. // Remove from engine
  13153. index = this._engine.scenes.indexOf(this);
  13154. if (index > -1) {
  13155. this._engine.scenes.splice(index, 1);
  13156. }
  13157. this._engine.wipeCaches();
  13158. };
  13159. // Release sounds & sounds tracks
  13160. Scene.prototype.disposeSounds = function () {
  13161. this.mainSoundTrack.dispose();
  13162. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13163. this.soundTracks[scIndex].dispose();
  13164. }
  13165. };
  13166. // Octrees
  13167. Scene.prototype.getWorldExtends = function () {
  13168. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13169. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13170. for (var index = 0; index < this.meshes.length; index++) {
  13171. var mesh = this.meshes[index];
  13172. mesh.computeWorldMatrix(true);
  13173. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13174. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13175. BABYLON.Tools.CheckExtends(minBox, min, max);
  13176. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13177. }
  13178. return {
  13179. min: min,
  13180. max: max
  13181. };
  13182. };
  13183. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13184. if (maxCapacity === void 0) { maxCapacity = 64; }
  13185. if (maxDepth === void 0) { maxDepth = 2; }
  13186. if (!this._selectionOctree) {
  13187. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13188. }
  13189. var worldExtends = this.getWorldExtends();
  13190. // Update octree
  13191. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13192. return this._selectionOctree;
  13193. };
  13194. // Picking
  13195. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13196. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13197. var engine = this._engine;
  13198. if (!camera) {
  13199. if (!this.activeCamera)
  13200. throw new Error("Active camera not set");
  13201. camera = this.activeCamera;
  13202. }
  13203. var cameraViewport = camera.viewport;
  13204. var viewport = cameraViewport.toGlobal(engine);
  13205. // Moving coordinates to local viewport world
  13206. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13207. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13208. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13209. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13210. };
  13211. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13212. var engine = this._engine;
  13213. if (!camera) {
  13214. if (!this.activeCamera)
  13215. throw new Error("Active camera not set");
  13216. camera = this.activeCamera;
  13217. }
  13218. var cameraViewport = camera.viewport;
  13219. var viewport = cameraViewport.toGlobal(engine);
  13220. var identity = BABYLON.Matrix.Identity();
  13221. // Moving coordinates to local viewport world
  13222. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13223. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13224. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13225. };
  13226. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13227. var pickingInfo = null;
  13228. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13229. var mesh = this.meshes[meshIndex];
  13230. if (predicate) {
  13231. if (!predicate(mesh)) {
  13232. continue;
  13233. }
  13234. }
  13235. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13236. continue;
  13237. }
  13238. var world = mesh.getWorldMatrix();
  13239. var ray = rayFunction(world);
  13240. var result = mesh.intersects(ray, fastCheck);
  13241. if (!result || !result.hit)
  13242. continue;
  13243. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13244. continue;
  13245. pickingInfo = result;
  13246. if (fastCheck) {
  13247. break;
  13248. }
  13249. }
  13250. return pickingInfo || new BABYLON.PickingInfo();
  13251. };
  13252. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13253. var pickingInfo = null;
  13254. camera = camera || this.activeCamera;
  13255. if (this.spriteManagers.length > 0) {
  13256. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13257. var spriteManager = this.spriteManagers[spriteIndex];
  13258. if (!spriteManager.isPickable) {
  13259. continue;
  13260. }
  13261. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13262. if (!result || !result.hit)
  13263. continue;
  13264. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13265. continue;
  13266. pickingInfo = result;
  13267. if (fastCheck) {
  13268. break;
  13269. }
  13270. }
  13271. }
  13272. return pickingInfo || new BABYLON.PickingInfo();
  13273. };
  13274. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13275. var _this = this;
  13276. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13277. /// <param name="x">X position on screen</param>
  13278. /// <param name="y">Y position on screen</param>
  13279. /// <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>
  13280. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13281. /// <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>
  13282. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13283. };
  13284. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13285. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13286. /// <param name="x">X position on screen</param>
  13287. /// <param name="y">Y position on screen</param>
  13288. /// <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>
  13289. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13290. /// <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>
  13291. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13292. };
  13293. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13294. var _this = this;
  13295. return this._internalPick(function (world) {
  13296. if (!_this._pickWithRayInverseMatrix) {
  13297. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13298. }
  13299. world.invertToRef(_this._pickWithRayInverseMatrix);
  13300. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13301. }, predicate, fastCheck);
  13302. };
  13303. Scene.prototype.setPointerOverMesh = function (mesh) {
  13304. if (this._pointerOverMesh === mesh) {
  13305. return;
  13306. }
  13307. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13308. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13309. }
  13310. this._pointerOverMesh = mesh;
  13311. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13312. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13313. }
  13314. };
  13315. Scene.prototype.getPointerOverMesh = function () {
  13316. return this._pointerOverMesh;
  13317. };
  13318. // Physics
  13319. Scene.prototype.getPhysicsEngine = function () {
  13320. return this._physicsEngine;
  13321. };
  13322. /**
  13323. * Enables physics to the current scene
  13324. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13325. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13326. * @return {boolean} was the physics engine initialized
  13327. */
  13328. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13329. if (this._physicsEngine) {
  13330. return true;
  13331. }
  13332. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13333. if (!this._physicsEngine.isSupported()) {
  13334. this._physicsEngine = null;
  13335. return false;
  13336. }
  13337. this._physicsEngine._initialize(gravity);
  13338. return true;
  13339. };
  13340. Scene.prototype.disablePhysicsEngine = function () {
  13341. if (!this._physicsEngine) {
  13342. return;
  13343. }
  13344. this._physicsEngine.dispose();
  13345. this._physicsEngine = undefined;
  13346. };
  13347. Scene.prototype.isPhysicsEnabled = function () {
  13348. return this._physicsEngine !== undefined;
  13349. };
  13350. /**
  13351. * Sets the gravity of the physics engine (and NOT of the scene)
  13352. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13353. */
  13354. Scene.prototype.setGravity = function (gravity) {
  13355. if (!this._physicsEngine) {
  13356. return;
  13357. }
  13358. this._physicsEngine._setGravity(gravity);
  13359. };
  13360. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13361. if (parts.parts) {
  13362. options = parts;
  13363. parts = parts.parts;
  13364. }
  13365. if (!this._physicsEngine) {
  13366. return null;
  13367. }
  13368. for (var index = 0; index < parts.length; index++) {
  13369. var mesh = parts[index].mesh;
  13370. mesh._physicImpostor = parts[index].impostor;
  13371. mesh._physicsMass = options.mass / parts.length;
  13372. mesh._physicsFriction = options.friction;
  13373. mesh._physicRestitution = options.restitution;
  13374. }
  13375. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13376. };
  13377. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13378. for (var index = 0; index < compound.parts.length; index++) {
  13379. var mesh = compound.parts[index].mesh;
  13380. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13381. this._physicsEngine._unregisterMesh(mesh);
  13382. }
  13383. };
  13384. // Misc.
  13385. Scene.prototype.createDefaultCameraOrLight = function () {
  13386. // Light
  13387. if (this.lights.length === 0) {
  13388. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13389. }
  13390. // Camera
  13391. if (!this.activeCamera) {
  13392. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13393. // Compute position
  13394. var worldExtends = this.getWorldExtends();
  13395. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13396. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13397. camera.setTarget(worldCenter);
  13398. this.activeCamera = camera;
  13399. }
  13400. };
  13401. // Tags
  13402. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13403. if (tagsQuery === undefined) {
  13404. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13405. return list;
  13406. }
  13407. var listByTags = [];
  13408. forEach = forEach || (function (item) { return; });
  13409. for (var i in list) {
  13410. var item = list[i];
  13411. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13412. listByTags.push(item);
  13413. forEach(item);
  13414. }
  13415. }
  13416. return listByTags;
  13417. };
  13418. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13419. return this._getByTags(this.meshes, tagsQuery, forEach);
  13420. };
  13421. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13422. return this._getByTags(this.cameras, tagsQuery, forEach);
  13423. };
  13424. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13425. return this._getByTags(this.lights, tagsQuery, forEach);
  13426. };
  13427. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13428. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13429. };
  13430. // Statics
  13431. Scene._FOGMODE_NONE = 0;
  13432. Scene._FOGMODE_EXP = 1;
  13433. Scene._FOGMODE_EXP2 = 2;
  13434. Scene._FOGMODE_LINEAR = 3;
  13435. Scene.MinDeltaTime = 1.0;
  13436. Scene.MaxDeltaTime = 1000.0;
  13437. return Scene;
  13438. })();
  13439. BABYLON.Scene = Scene;
  13440. })(BABYLON || (BABYLON = {}));
  13441. var BABYLON;
  13442. (function (BABYLON) {
  13443. var VertexBuffer = (function () {
  13444. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13445. if (engine instanceof BABYLON.Mesh) {
  13446. this._engine = engine.getScene().getEngine();
  13447. }
  13448. else {
  13449. this._engine = engine;
  13450. }
  13451. this._updatable = updatable;
  13452. this._data = data;
  13453. if (!postponeInternalCreation) {
  13454. this.create();
  13455. }
  13456. this._kind = kind;
  13457. if (stride) {
  13458. this._strideSize = stride;
  13459. return;
  13460. }
  13461. // Deduce stride from kind
  13462. switch (kind) {
  13463. case VertexBuffer.PositionKind:
  13464. this._strideSize = 3;
  13465. break;
  13466. case VertexBuffer.NormalKind:
  13467. this._strideSize = 3;
  13468. break;
  13469. case VertexBuffer.UVKind:
  13470. case VertexBuffer.UV2Kind:
  13471. case VertexBuffer.UV3Kind:
  13472. case VertexBuffer.UV4Kind:
  13473. case VertexBuffer.UV5Kind:
  13474. case VertexBuffer.UV6Kind:
  13475. this._strideSize = 2;
  13476. break;
  13477. case VertexBuffer.ColorKind:
  13478. this._strideSize = 4;
  13479. break;
  13480. case VertexBuffer.MatricesIndicesKind:
  13481. this._strideSize = 4;
  13482. break;
  13483. case VertexBuffer.MatricesWeightsKind:
  13484. this._strideSize = 4;
  13485. break;
  13486. }
  13487. }
  13488. // Properties
  13489. VertexBuffer.prototype.isUpdatable = function () {
  13490. return this._updatable;
  13491. };
  13492. VertexBuffer.prototype.getData = function () {
  13493. return this._data;
  13494. };
  13495. VertexBuffer.prototype.getBuffer = function () {
  13496. return this._buffer;
  13497. };
  13498. VertexBuffer.prototype.getStrideSize = function () {
  13499. return this._strideSize;
  13500. };
  13501. // Methods
  13502. VertexBuffer.prototype.create = function (data) {
  13503. if (!data && this._buffer) {
  13504. return; // nothing to do
  13505. }
  13506. data = data || this._data;
  13507. if (!this._buffer) {
  13508. if (this._updatable) {
  13509. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13510. }
  13511. else {
  13512. this._buffer = this._engine.createVertexBuffer(data);
  13513. }
  13514. }
  13515. if (this._updatable) {
  13516. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13517. this._data = data;
  13518. }
  13519. };
  13520. VertexBuffer.prototype.update = function (data) {
  13521. this.create(data);
  13522. };
  13523. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13524. if (!this._buffer) {
  13525. return;
  13526. }
  13527. if (this._updatable) {
  13528. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13529. this._data = null;
  13530. }
  13531. };
  13532. VertexBuffer.prototype.dispose = function () {
  13533. if (!this._buffer) {
  13534. return;
  13535. }
  13536. if (this._engine._releaseBuffer(this._buffer)) {
  13537. this._buffer = null;
  13538. }
  13539. };
  13540. Object.defineProperty(VertexBuffer, "PositionKind", {
  13541. get: function () {
  13542. return VertexBuffer._PositionKind;
  13543. },
  13544. enumerable: true,
  13545. configurable: true
  13546. });
  13547. Object.defineProperty(VertexBuffer, "NormalKind", {
  13548. get: function () {
  13549. return VertexBuffer._NormalKind;
  13550. },
  13551. enumerable: true,
  13552. configurable: true
  13553. });
  13554. Object.defineProperty(VertexBuffer, "UVKind", {
  13555. get: function () {
  13556. return VertexBuffer._UVKind;
  13557. },
  13558. enumerable: true,
  13559. configurable: true
  13560. });
  13561. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13562. get: function () {
  13563. return VertexBuffer._UV2Kind;
  13564. },
  13565. enumerable: true,
  13566. configurable: true
  13567. });
  13568. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13569. get: function () {
  13570. return VertexBuffer._UV3Kind;
  13571. },
  13572. enumerable: true,
  13573. configurable: true
  13574. });
  13575. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13576. get: function () {
  13577. return VertexBuffer._UV4Kind;
  13578. },
  13579. enumerable: true,
  13580. configurable: true
  13581. });
  13582. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13583. get: function () {
  13584. return VertexBuffer._UV5Kind;
  13585. },
  13586. enumerable: true,
  13587. configurable: true
  13588. });
  13589. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13590. get: function () {
  13591. return VertexBuffer._UV6Kind;
  13592. },
  13593. enumerable: true,
  13594. configurable: true
  13595. });
  13596. Object.defineProperty(VertexBuffer, "ColorKind", {
  13597. get: function () {
  13598. return VertexBuffer._ColorKind;
  13599. },
  13600. enumerable: true,
  13601. configurable: true
  13602. });
  13603. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13604. get: function () {
  13605. return VertexBuffer._MatricesIndicesKind;
  13606. },
  13607. enumerable: true,
  13608. configurable: true
  13609. });
  13610. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13611. get: function () {
  13612. return VertexBuffer._MatricesWeightsKind;
  13613. },
  13614. enumerable: true,
  13615. configurable: true
  13616. });
  13617. // Enums
  13618. VertexBuffer._PositionKind = "position";
  13619. VertexBuffer._NormalKind = "normal";
  13620. VertexBuffer._UVKind = "uv";
  13621. VertexBuffer._UV2Kind = "uv2";
  13622. VertexBuffer._UV3Kind = "uv3";
  13623. VertexBuffer._UV4Kind = "uv4";
  13624. VertexBuffer._UV5Kind = "uv5";
  13625. VertexBuffer._UV6Kind = "uv6";
  13626. VertexBuffer._ColorKind = "color";
  13627. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13628. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13629. return VertexBuffer;
  13630. })();
  13631. BABYLON.VertexBuffer = VertexBuffer;
  13632. })(BABYLON || (BABYLON = {}));
  13633. var BABYLON;
  13634. (function (BABYLON) {
  13635. /**
  13636. * Creates an instance based on a source mesh.
  13637. */
  13638. var InstancedMesh = (function (_super) {
  13639. __extends(InstancedMesh, _super);
  13640. function InstancedMesh(name, source) {
  13641. _super.call(this, name, source.getScene());
  13642. source.instances.push(this);
  13643. this._sourceMesh = source;
  13644. this.position.copyFrom(source.position);
  13645. this.rotation.copyFrom(source.rotation);
  13646. this.scaling.copyFrom(source.scaling);
  13647. if (source.rotationQuaternion) {
  13648. this.rotationQuaternion = source.rotationQuaternion.clone();
  13649. }
  13650. this.infiniteDistance = source.infiniteDistance;
  13651. this.setPivotMatrix(source.getPivotMatrix());
  13652. this.refreshBoundingInfo();
  13653. this._syncSubMeshes();
  13654. }
  13655. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13656. // Methods
  13657. get: function () {
  13658. return this._sourceMesh.receiveShadows;
  13659. },
  13660. enumerable: true,
  13661. configurable: true
  13662. });
  13663. Object.defineProperty(InstancedMesh.prototype, "material", {
  13664. get: function () {
  13665. return this._sourceMesh.material;
  13666. },
  13667. enumerable: true,
  13668. configurable: true
  13669. });
  13670. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13671. get: function () {
  13672. return this._sourceMesh.visibility;
  13673. },
  13674. enumerable: true,
  13675. configurable: true
  13676. });
  13677. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13678. get: function () {
  13679. return this._sourceMesh.skeleton;
  13680. },
  13681. enumerable: true,
  13682. configurable: true
  13683. });
  13684. InstancedMesh.prototype.getTotalVertices = function () {
  13685. return this._sourceMesh.getTotalVertices();
  13686. };
  13687. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13688. get: function () {
  13689. return this._sourceMesh;
  13690. },
  13691. enumerable: true,
  13692. configurable: true
  13693. });
  13694. InstancedMesh.prototype.getVerticesData = function (kind) {
  13695. return this._sourceMesh.getVerticesData(kind);
  13696. };
  13697. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13698. return this._sourceMesh.isVerticesDataPresent(kind);
  13699. };
  13700. InstancedMesh.prototype.getIndices = function () {
  13701. return this._sourceMesh.getIndices();
  13702. };
  13703. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13704. get: function () {
  13705. return this._sourceMesh._positions;
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13711. var meshBB = this._sourceMesh.getBoundingInfo();
  13712. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13713. this._updateBoundingInfo();
  13714. };
  13715. InstancedMesh.prototype._preActivate = function () {
  13716. if (this._currentLOD) {
  13717. this._currentLOD._preActivate();
  13718. }
  13719. };
  13720. InstancedMesh.prototype._activate = function (renderId) {
  13721. if (this._currentLOD) {
  13722. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13723. }
  13724. };
  13725. InstancedMesh.prototype.getLOD = function (camera) {
  13726. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13727. if (this._currentLOD === this.sourceMesh) {
  13728. return this;
  13729. }
  13730. return this._currentLOD;
  13731. };
  13732. InstancedMesh.prototype._syncSubMeshes = function () {
  13733. this.releaseSubMeshes();
  13734. if (this._sourceMesh.subMeshes) {
  13735. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13736. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13737. }
  13738. }
  13739. };
  13740. InstancedMesh.prototype._generatePointsArray = function () {
  13741. return this._sourceMesh._generatePointsArray();
  13742. };
  13743. // Clone
  13744. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13745. var result = this._sourceMesh.createInstance(name);
  13746. // Deep copy
  13747. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13748. // Bounding info
  13749. this.refreshBoundingInfo();
  13750. // Parent
  13751. if (newParent) {
  13752. result.parent = newParent;
  13753. }
  13754. if (!doNotCloneChildren) {
  13755. // Children
  13756. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13757. var mesh = this.getScene().meshes[index];
  13758. if (mesh.parent === this) {
  13759. mesh.clone(mesh.name, result);
  13760. }
  13761. }
  13762. }
  13763. result.computeWorldMatrix(true);
  13764. return result;
  13765. };
  13766. // Dispoe
  13767. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13768. // Remove from mesh
  13769. var index = this._sourceMesh.instances.indexOf(this);
  13770. this._sourceMesh.instances.splice(index, 1);
  13771. _super.prototype.dispose.call(this, doNotRecurse);
  13772. };
  13773. return InstancedMesh;
  13774. })(BABYLON.AbstractMesh);
  13775. BABYLON.InstancedMesh = InstancedMesh;
  13776. })(BABYLON || (BABYLON = {}));
  13777. var BABYLON;
  13778. (function (BABYLON) {
  13779. var _InstancesBatch = (function () {
  13780. function _InstancesBatch() {
  13781. this.mustReturn = false;
  13782. this.visibleInstances = new Array();
  13783. this.renderSelf = new Array();
  13784. }
  13785. return _InstancesBatch;
  13786. })();
  13787. BABYLON._InstancesBatch = _InstancesBatch;
  13788. var Mesh = (function (_super) {
  13789. __extends(Mesh, _super);
  13790. /**
  13791. * @constructor
  13792. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13793. * @param {Scene} scene - The scene to add this mesh to.
  13794. * @param {Node} parent - The parent of this mesh, if it has one
  13795. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13796. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13797. * When false, achieved by calling a clone(), also passing False.
  13798. * This will make creation of children, recursive.
  13799. */
  13800. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13801. if (parent === void 0) { parent = null; }
  13802. _super.call(this, name, scene);
  13803. // Members
  13804. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13805. this.instances = new Array();
  13806. this._LODLevels = new Array();
  13807. this._onBeforeRenderCallbacks = new Array();
  13808. this._onAfterRenderCallbacks = new Array();
  13809. this._visibleInstances = {};
  13810. this._renderIdForInstances = new Array();
  13811. this._batchCache = new _InstancesBatch();
  13812. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13813. this._sideOrientation = Mesh._DEFAULTSIDE;
  13814. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13815. if (source) {
  13816. // Geometry
  13817. if (source._geometry) {
  13818. source._geometry.applyToMesh(this);
  13819. }
  13820. // Deep copy
  13821. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13822. this.id = name + "." + source.id;
  13823. // Material
  13824. this.material = source.material;
  13825. var index;
  13826. if (!doNotCloneChildren) {
  13827. // Children
  13828. for (index = 0; index < scene.meshes.length; index++) {
  13829. var mesh = scene.meshes[index];
  13830. if (mesh.parent === source) {
  13831. // doNotCloneChildren is always going to be False
  13832. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13833. }
  13834. }
  13835. }
  13836. // Particles
  13837. for (index = 0; index < scene.particleSystems.length; index++) {
  13838. var system = scene.particleSystems[index];
  13839. if (system.emitter === source) {
  13840. system.clone(system.name, this);
  13841. }
  13842. }
  13843. this.computeWorldMatrix(true);
  13844. }
  13845. // Parent
  13846. if (parent !== null) {
  13847. this.parent = parent;
  13848. }
  13849. }
  13850. Object.defineProperty(Mesh, "FRONTSIDE", {
  13851. get: function () {
  13852. return Mesh._FRONTSIDE;
  13853. },
  13854. enumerable: true,
  13855. configurable: true
  13856. });
  13857. Object.defineProperty(Mesh, "BACKSIDE", {
  13858. get: function () {
  13859. return Mesh._BACKSIDE;
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13865. get: function () {
  13866. return Mesh._DOUBLESIDE;
  13867. },
  13868. enumerable: true,
  13869. configurable: true
  13870. });
  13871. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13872. get: function () {
  13873. return Mesh._DEFAULTSIDE;
  13874. },
  13875. enumerable: true,
  13876. configurable: true
  13877. });
  13878. Object.defineProperty(Mesh, "NO_CAP", {
  13879. get: function () {
  13880. return Mesh._NO_CAP;
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(Mesh, "CAP_START", {
  13886. get: function () {
  13887. return Mesh._CAP_START;
  13888. },
  13889. enumerable: true,
  13890. configurable: true
  13891. });
  13892. Object.defineProperty(Mesh, "CAP_END", {
  13893. get: function () {
  13894. return Mesh._CAP_END;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. Object.defineProperty(Mesh, "CAP_ALL", {
  13900. get: function () {
  13901. return Mesh._CAP_ALL;
  13902. },
  13903. enumerable: true,
  13904. configurable: true
  13905. });
  13906. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13907. // Methods
  13908. get: function () {
  13909. return this._LODLevels.length > 0;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Mesh.prototype._sortLODLevels = function () {
  13915. this._LODLevels.sort(function (a, b) {
  13916. if (a.distance < b.distance) {
  13917. return 1;
  13918. }
  13919. if (a.distance > b.distance) {
  13920. return -1;
  13921. }
  13922. return 0;
  13923. });
  13924. };
  13925. /**
  13926. * Add a mesh as LOD level triggered at the given distance.
  13927. * @param {number} distance - the distance from the center of the object to show this level
  13928. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13929. * @return {BABYLON.Mesh} this mesh (for chaining)
  13930. */
  13931. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13932. if (mesh && mesh._masterMesh) {
  13933. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13934. return this;
  13935. }
  13936. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13937. this._LODLevels.push(level);
  13938. if (mesh) {
  13939. mesh._masterMesh = this;
  13940. }
  13941. this._sortLODLevels();
  13942. return this;
  13943. };
  13944. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13945. for (var index = 0; index < this._LODLevels.length; index++) {
  13946. var level = this._LODLevels[index];
  13947. if (level.distance === distance) {
  13948. return level.mesh;
  13949. }
  13950. }
  13951. return null;
  13952. };
  13953. /**
  13954. * Remove a mesh from the LOD array
  13955. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13956. * @return {BABYLON.Mesh} this mesh (for chaining)
  13957. */
  13958. Mesh.prototype.removeLODLevel = function (mesh) {
  13959. for (var index = 0; index < this._LODLevels.length; index++) {
  13960. if (this._LODLevels[index].mesh === mesh) {
  13961. this._LODLevels.splice(index, 1);
  13962. if (mesh) {
  13963. mesh._masterMesh = null;
  13964. }
  13965. }
  13966. }
  13967. this._sortLODLevels();
  13968. return this;
  13969. };
  13970. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13971. if (!this._LODLevels || this._LODLevels.length === 0) {
  13972. return this;
  13973. }
  13974. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13975. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13976. if (this.onLODLevelSelection) {
  13977. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13978. }
  13979. return this;
  13980. }
  13981. for (var index = 0; index < this._LODLevels.length; index++) {
  13982. var level = this._LODLevels[index];
  13983. if (level.distance < distanceToCamera) {
  13984. if (level.mesh) {
  13985. level.mesh._preActivate();
  13986. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13987. }
  13988. if (this.onLODLevelSelection) {
  13989. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13990. }
  13991. return level.mesh;
  13992. }
  13993. }
  13994. if (this.onLODLevelSelection) {
  13995. this.onLODLevelSelection(distanceToCamera, this, this);
  13996. }
  13997. return this;
  13998. };
  13999. Object.defineProperty(Mesh.prototype, "geometry", {
  14000. get: function () {
  14001. return this._geometry;
  14002. },
  14003. enumerable: true,
  14004. configurable: true
  14005. });
  14006. Mesh.prototype.getTotalVertices = function () {
  14007. if (!this._geometry) {
  14008. return 0;
  14009. }
  14010. return this._geometry.getTotalVertices();
  14011. };
  14012. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14013. if (!this._geometry) {
  14014. return null;
  14015. }
  14016. return this._geometry.getVerticesData(kind, copyWhenShared);
  14017. };
  14018. Mesh.prototype.getVertexBuffer = function (kind) {
  14019. if (!this._geometry) {
  14020. return undefined;
  14021. }
  14022. return this._geometry.getVertexBuffer(kind);
  14023. };
  14024. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14025. if (!this._geometry) {
  14026. if (this._delayInfo) {
  14027. return this._delayInfo.indexOf(kind) !== -1;
  14028. }
  14029. return false;
  14030. }
  14031. return this._geometry.isVerticesDataPresent(kind);
  14032. };
  14033. Mesh.prototype.getVerticesDataKinds = function () {
  14034. if (!this._geometry) {
  14035. var result = [];
  14036. if (this._delayInfo) {
  14037. for (var kind in this._delayInfo) {
  14038. result.push(kind);
  14039. }
  14040. }
  14041. return result;
  14042. }
  14043. return this._geometry.getVerticesDataKinds();
  14044. };
  14045. Mesh.prototype.getTotalIndices = function () {
  14046. if (!this._geometry) {
  14047. return 0;
  14048. }
  14049. return this._geometry.getTotalIndices();
  14050. };
  14051. Mesh.prototype.getIndices = function (copyWhenShared) {
  14052. if (!this._geometry) {
  14053. return [];
  14054. }
  14055. return this._geometry.getIndices(copyWhenShared);
  14056. };
  14057. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14058. get: function () {
  14059. return this._masterMesh !== null && this._masterMesh !== undefined;
  14060. },
  14061. enumerable: true,
  14062. configurable: true
  14063. });
  14064. Mesh.prototype.isReady = function () {
  14065. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14066. return false;
  14067. }
  14068. return _super.prototype.isReady.call(this);
  14069. };
  14070. Mesh.prototype.isDisposed = function () {
  14071. return this._isDisposed;
  14072. };
  14073. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14074. get: function () {
  14075. return this._sideOrientation;
  14076. },
  14077. set: function (sideO) {
  14078. this._sideOrientation = sideO;
  14079. },
  14080. enumerable: true,
  14081. configurable: true
  14082. });
  14083. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14084. get: function () {
  14085. return this._areNormalsFrozen;
  14086. },
  14087. enumerable: true,
  14088. configurable: true
  14089. });
  14090. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14091. Mesh.prototype.freezeNormals = function () {
  14092. this._areNormalsFrozen = true;
  14093. };
  14094. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14095. Mesh.prototype.unfreezeNormals = function () {
  14096. this._areNormalsFrozen = false;
  14097. };
  14098. // Methods
  14099. Mesh.prototype._preActivate = function () {
  14100. var sceneRenderId = this.getScene().getRenderId();
  14101. if (this._preActivateId === sceneRenderId) {
  14102. return;
  14103. }
  14104. this._preActivateId = sceneRenderId;
  14105. this._visibleInstances = null;
  14106. };
  14107. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14108. if (!this._visibleInstances) {
  14109. this._visibleInstances = {};
  14110. this._visibleInstances.defaultRenderId = renderId;
  14111. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14112. }
  14113. if (!this._visibleInstances[renderId]) {
  14114. this._visibleInstances[renderId] = new Array();
  14115. }
  14116. this._visibleInstances[renderId].push(instance);
  14117. };
  14118. Mesh.prototype.refreshBoundingInfo = function () {
  14119. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14120. if (data) {
  14121. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14122. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14123. }
  14124. if (this.subMeshes) {
  14125. for (var index = 0; index < this.subMeshes.length; index++) {
  14126. this.subMeshes[index].refreshBoundingInfo();
  14127. }
  14128. }
  14129. this._updateBoundingInfo();
  14130. };
  14131. Mesh.prototype._createGlobalSubMesh = function () {
  14132. var totalVertices = this.getTotalVertices();
  14133. if (!totalVertices || !this.getIndices()) {
  14134. return null;
  14135. }
  14136. this.releaseSubMeshes();
  14137. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14138. };
  14139. Mesh.prototype.subdivide = function (count) {
  14140. if (count < 1) {
  14141. return;
  14142. }
  14143. var totalIndices = this.getTotalIndices();
  14144. var subdivisionSize = (totalIndices / count) | 0;
  14145. var offset = 0;
  14146. // Ensure that subdivisionSize is a multiple of 3
  14147. while (subdivisionSize % 3 !== 0) {
  14148. subdivisionSize++;
  14149. }
  14150. this.releaseSubMeshes();
  14151. for (var index = 0; index < count; index++) {
  14152. if (offset >= totalIndices) {
  14153. break;
  14154. }
  14155. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14156. offset += subdivisionSize;
  14157. }
  14158. this.synchronizeInstances();
  14159. };
  14160. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14161. if (!this._geometry) {
  14162. var vertexData = new BABYLON.VertexData();
  14163. vertexData.set(data, kind);
  14164. var scene = this.getScene();
  14165. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14166. }
  14167. else {
  14168. this._geometry.setVerticesData(kind, data, updatable, stride);
  14169. }
  14170. };
  14171. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14172. if (!this._geometry) {
  14173. return;
  14174. }
  14175. if (!makeItUnique) {
  14176. this._geometry.updateVerticesData(kind, data, updateExtends);
  14177. }
  14178. else {
  14179. this.makeGeometryUnique();
  14180. this.updateVerticesData(kind, data, updateExtends, false);
  14181. }
  14182. };
  14183. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14184. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14185. if (!this._geometry) {
  14186. return;
  14187. }
  14188. if (!makeItUnique) {
  14189. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14190. }
  14191. else {
  14192. this.makeGeometryUnique();
  14193. this.updateVerticesDataDirectly(kind, data, offset, false);
  14194. }
  14195. };
  14196. // Mesh positions update function :
  14197. // updates the mesh positions according to the positionFunction returned values.
  14198. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14199. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14200. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14201. if (computeNormals === void 0) { computeNormals = true; }
  14202. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14203. positionFunction(positions);
  14204. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14205. if (computeNormals) {
  14206. var indices = this.getIndices();
  14207. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14208. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14209. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14210. }
  14211. };
  14212. Mesh.prototype.makeGeometryUnique = function () {
  14213. if (!this._geometry) {
  14214. return;
  14215. }
  14216. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14217. geometry.applyToMesh(this);
  14218. };
  14219. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14220. if (!this._geometry) {
  14221. var vertexData = new BABYLON.VertexData();
  14222. vertexData.indices = indices;
  14223. var scene = this.getScene();
  14224. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14225. }
  14226. else {
  14227. this._geometry.setIndices(indices, totalVertices);
  14228. }
  14229. };
  14230. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14231. var engine = this.getScene().getEngine();
  14232. // Wireframe
  14233. var indexToBind;
  14234. switch (fillMode) {
  14235. case BABYLON.Material.PointFillMode:
  14236. indexToBind = null;
  14237. break;
  14238. case BABYLON.Material.WireFrameFillMode:
  14239. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14240. break;
  14241. default:
  14242. case BABYLON.Material.TriangleFillMode:
  14243. indexToBind = this._geometry.getIndexBuffer();
  14244. break;
  14245. }
  14246. // VBOs
  14247. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14248. };
  14249. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14250. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14251. return;
  14252. }
  14253. var engine = this.getScene().getEngine();
  14254. // Draw order
  14255. switch (fillMode) {
  14256. case BABYLON.Material.PointFillMode:
  14257. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14258. break;
  14259. case BABYLON.Material.WireFrameFillMode:
  14260. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14261. break;
  14262. default:
  14263. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14264. }
  14265. };
  14266. Mesh.prototype.registerBeforeRender = function (func) {
  14267. this._onBeforeRenderCallbacks.push(func);
  14268. };
  14269. Mesh.prototype.unregisterBeforeRender = function (func) {
  14270. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14271. if (index > -1) {
  14272. this._onBeforeRenderCallbacks.splice(index, 1);
  14273. }
  14274. };
  14275. Mesh.prototype.registerAfterRender = function (func) {
  14276. this._onAfterRenderCallbacks.push(func);
  14277. };
  14278. Mesh.prototype.unregisterAfterRender = function (func) {
  14279. var index = this._onAfterRenderCallbacks.indexOf(func);
  14280. if (index > -1) {
  14281. this._onAfterRenderCallbacks.splice(index, 1);
  14282. }
  14283. };
  14284. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14285. var scene = this.getScene();
  14286. this._batchCache.mustReturn = false;
  14287. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14288. this._batchCache.visibleInstances[subMeshId] = null;
  14289. if (this._visibleInstances) {
  14290. var currentRenderId = scene.getRenderId();
  14291. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14292. var selfRenderId = this._renderId;
  14293. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14294. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14295. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14296. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14297. }
  14298. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14299. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14300. this._batchCache.mustReturn = true;
  14301. return this._batchCache;
  14302. }
  14303. if (currentRenderId !== selfRenderId) {
  14304. this._batchCache.renderSelf[subMeshId] = false;
  14305. }
  14306. }
  14307. this._renderIdForInstances[subMeshId] = currentRenderId;
  14308. }
  14309. return this._batchCache;
  14310. };
  14311. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14312. var visibleInstances = batch.visibleInstances[subMesh._id];
  14313. var matricesCount = visibleInstances.length + 1;
  14314. var bufferSize = matricesCount * 16 * 4;
  14315. while (this._instancesBufferSize < bufferSize) {
  14316. this._instancesBufferSize *= 2;
  14317. }
  14318. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14319. if (this._worldMatricesInstancesBuffer) {
  14320. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14321. }
  14322. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14323. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14324. }
  14325. var offset = 0;
  14326. var instancesCount = 0;
  14327. var world = this.getWorldMatrix();
  14328. if (batch.renderSelf[subMesh._id]) {
  14329. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14330. offset += 16;
  14331. instancesCount++;
  14332. }
  14333. if (visibleInstances) {
  14334. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14335. var instance = visibleInstances[instanceIndex];
  14336. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14337. offset += 16;
  14338. instancesCount++;
  14339. }
  14340. }
  14341. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14342. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14343. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14344. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14345. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14346. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14347. this._draw(subMesh, fillMode, instancesCount);
  14348. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14349. };
  14350. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14351. var scene = this.getScene();
  14352. var engine = scene.getEngine();
  14353. if (hardwareInstancedRendering) {
  14354. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14355. }
  14356. else {
  14357. if (batch.renderSelf[subMesh._id]) {
  14358. // Draw
  14359. if (onBeforeDraw) {
  14360. onBeforeDraw(false, this.getWorldMatrix());
  14361. }
  14362. this._draw(subMesh, fillMode);
  14363. }
  14364. if (batch.visibleInstances[subMesh._id]) {
  14365. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14366. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14367. // World
  14368. var world = instance.getWorldMatrix();
  14369. if (onBeforeDraw) {
  14370. onBeforeDraw(true, world);
  14371. }
  14372. // Draw
  14373. this._draw(subMesh, fillMode);
  14374. }
  14375. }
  14376. }
  14377. };
  14378. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14379. var scene = this.getScene();
  14380. // Managing instances
  14381. var batch = this._getInstancesRenderList(subMesh._id);
  14382. if (batch.mustReturn) {
  14383. return;
  14384. }
  14385. // Checking geometry state
  14386. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14387. return;
  14388. }
  14389. var callbackIndex;
  14390. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14391. this._onBeforeRenderCallbacks[callbackIndex](this);
  14392. }
  14393. var engine = scene.getEngine();
  14394. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14395. // Material
  14396. var effectiveMaterial = subMesh.getMaterial();
  14397. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14398. return;
  14399. }
  14400. // Outline - step 1
  14401. var savedDepthWrite = engine.getDepthWrite();
  14402. if (this.renderOutline) {
  14403. engine.setDepthWrite(false);
  14404. scene.getOutlineRenderer().render(subMesh, batch);
  14405. engine.setDepthWrite(savedDepthWrite);
  14406. }
  14407. effectiveMaterial._preBind();
  14408. var effect = effectiveMaterial.getEffect();
  14409. // Bind
  14410. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14411. this._bind(subMesh, effect, fillMode);
  14412. var world = this.getWorldMatrix();
  14413. effectiveMaterial.bind(world, this);
  14414. // Alpha mode
  14415. if (enableAlphaMode) {
  14416. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14417. }
  14418. // Draw
  14419. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14420. if (isInstance) {
  14421. effectiveMaterial.bindOnlyWorldMatrix(world);
  14422. }
  14423. });
  14424. // Unbind
  14425. effectiveMaterial.unbind();
  14426. // Outline - step 2
  14427. if (this.renderOutline && savedDepthWrite) {
  14428. engine.setDepthWrite(true);
  14429. engine.setColorWrite(false);
  14430. scene.getOutlineRenderer().render(subMesh, batch);
  14431. engine.setColorWrite(true);
  14432. }
  14433. // Overlay
  14434. if (this.renderOverlay) {
  14435. var currentMode = engine.getAlphaMode();
  14436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14437. scene.getOutlineRenderer().render(subMesh, batch, true);
  14438. engine.setAlphaMode(currentMode);
  14439. }
  14440. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14441. this._onAfterRenderCallbacks[callbackIndex](this);
  14442. }
  14443. };
  14444. Mesh.prototype.getEmittedParticleSystems = function () {
  14445. var results = new Array();
  14446. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14447. var particleSystem = this.getScene().particleSystems[index];
  14448. if (particleSystem.emitter === this) {
  14449. results.push(particleSystem);
  14450. }
  14451. }
  14452. return results;
  14453. };
  14454. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14455. var results = new Array();
  14456. var descendants = this.getDescendants();
  14457. descendants.push(this);
  14458. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14459. var particleSystem = this.getScene().particleSystems[index];
  14460. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14461. results.push(particleSystem);
  14462. }
  14463. }
  14464. return results;
  14465. };
  14466. Mesh.prototype.getChildren = function () {
  14467. var results = [];
  14468. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14469. var mesh = this.getScene().meshes[index];
  14470. if (mesh.parent === this) {
  14471. results.push(mesh);
  14472. }
  14473. }
  14474. return results;
  14475. };
  14476. Mesh.prototype._checkDelayState = function () {
  14477. var _this = this;
  14478. var that = this;
  14479. var scene = this.getScene();
  14480. if (this._geometry) {
  14481. this._geometry.load(scene);
  14482. }
  14483. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14484. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14485. scene._addPendingData(that);
  14486. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14487. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14488. if (data instanceof ArrayBuffer) {
  14489. _this._delayLoadingFunction(data, _this);
  14490. }
  14491. else {
  14492. _this._delayLoadingFunction(JSON.parse(data), _this);
  14493. }
  14494. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14495. scene._removePendingData(_this);
  14496. }, function () { }, scene.database, getBinaryData);
  14497. }
  14498. };
  14499. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14500. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14501. return false;
  14502. }
  14503. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14504. return false;
  14505. }
  14506. this._checkDelayState();
  14507. return true;
  14508. };
  14509. Mesh.prototype.setMaterialByID = function (id) {
  14510. var materials = this.getScene().materials;
  14511. var index;
  14512. for (index = 0; index < materials.length; index++) {
  14513. if (materials[index].id === id) {
  14514. this.material = materials[index];
  14515. return;
  14516. }
  14517. }
  14518. // Multi
  14519. var multiMaterials = this.getScene().multiMaterials;
  14520. for (index = 0; index < multiMaterials.length; index++) {
  14521. if (multiMaterials[index].id === id) {
  14522. this.material = multiMaterials[index];
  14523. return;
  14524. }
  14525. }
  14526. };
  14527. Mesh.prototype.getAnimatables = function () {
  14528. var results = [];
  14529. if (this.material) {
  14530. results.push(this.material);
  14531. }
  14532. if (this.skeleton) {
  14533. results.push(this.skeleton);
  14534. }
  14535. return results;
  14536. };
  14537. // Geometry
  14538. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14539. // Position
  14540. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14541. return;
  14542. }
  14543. this._resetPointsArrayCache();
  14544. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14545. var temp = [];
  14546. var index;
  14547. for (index = 0; index < data.length; index += 3) {
  14548. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14549. }
  14550. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14551. // Normals
  14552. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14553. return;
  14554. }
  14555. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14556. temp = [];
  14557. for (index = 0; index < data.length; index += 3) {
  14558. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14559. }
  14560. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14561. // flip faces?
  14562. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14563. this.flipFaces();
  14564. }
  14565. };
  14566. // Will apply current transform to mesh and reset world matrix
  14567. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14568. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14569. this.scaling.copyFromFloats(1, 1, 1);
  14570. this.position.copyFromFloats(0, 0, 0);
  14571. this.rotation.copyFromFloats(0, 0, 0);
  14572. //only if quaternion is already set
  14573. if (this.rotationQuaternion) {
  14574. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14575. }
  14576. this._worldMatrix = BABYLON.Matrix.Identity();
  14577. };
  14578. // Cache
  14579. Mesh.prototype._resetPointsArrayCache = function () {
  14580. this._positions = null;
  14581. };
  14582. Mesh.prototype._generatePointsArray = function () {
  14583. if (this._positions)
  14584. return true;
  14585. this._positions = [];
  14586. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14587. if (!data) {
  14588. return false;
  14589. }
  14590. for (var index = 0; index < data.length; index += 3) {
  14591. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14592. }
  14593. return true;
  14594. };
  14595. // Clone
  14596. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14597. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14598. };
  14599. // Dispose
  14600. Mesh.prototype.dispose = function (doNotRecurse) {
  14601. if (this._geometry) {
  14602. this._geometry.releaseForMesh(this, true);
  14603. }
  14604. // Instances
  14605. if (this._worldMatricesInstancesBuffer) {
  14606. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14607. this._worldMatricesInstancesBuffer = null;
  14608. }
  14609. while (this.instances.length) {
  14610. this.instances[0].dispose();
  14611. }
  14612. _super.prototype.dispose.call(this, doNotRecurse);
  14613. };
  14614. // Geometric tools
  14615. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14616. var _this = this;
  14617. var scene = this.getScene();
  14618. var onload = function (img) {
  14619. // Getting height map data
  14620. var canvas = document.createElement("canvas");
  14621. var context = canvas.getContext("2d");
  14622. var heightMapWidth = img.width;
  14623. var heightMapHeight = img.height;
  14624. canvas.width = heightMapWidth;
  14625. canvas.height = heightMapHeight;
  14626. context.drawImage(img, 0, 0);
  14627. // Create VertexData from map data
  14628. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14629. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14630. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14631. //execute success callback, if set
  14632. if (onSuccess) {
  14633. onSuccess(_this);
  14634. }
  14635. };
  14636. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14637. };
  14638. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14639. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14640. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14641. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14642. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14643. return;
  14644. }
  14645. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14646. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14647. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14648. var position = BABYLON.Vector3.Zero();
  14649. var normal = BABYLON.Vector3.Zero();
  14650. var uv = BABYLON.Vector2.Zero();
  14651. for (var index = 0; index < positions.length; index += 3) {
  14652. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14653. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14654. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14655. // Compute height
  14656. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14657. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14658. var pos = (u + v * heightMapWidth) * 4;
  14659. var r = buffer[pos] / 255.0;
  14660. var g = buffer[pos + 1] / 255.0;
  14661. var b = buffer[pos + 2] / 255.0;
  14662. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14663. normal.normalize();
  14664. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14665. position = position.add(normal);
  14666. position.toArray(positions, index);
  14667. }
  14668. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14669. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14670. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14671. };
  14672. Mesh.prototype.convertToFlatShadedMesh = function () {
  14673. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14674. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14675. var kinds = this.getVerticesDataKinds();
  14676. var vbs = [];
  14677. var data = [];
  14678. var newdata = [];
  14679. var updatableNormals = false;
  14680. var kindIndex;
  14681. var kind;
  14682. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14683. kind = kinds[kindIndex];
  14684. var vertexBuffer = this.getVertexBuffer(kind);
  14685. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14686. updatableNormals = vertexBuffer.isUpdatable();
  14687. kinds.splice(kindIndex, 1);
  14688. kindIndex--;
  14689. continue;
  14690. }
  14691. vbs[kind] = vertexBuffer;
  14692. data[kind] = vbs[kind].getData();
  14693. newdata[kind] = [];
  14694. }
  14695. // Save previous submeshes
  14696. var previousSubmeshes = this.subMeshes.slice(0);
  14697. var indices = this.getIndices();
  14698. var totalIndices = this.getTotalIndices();
  14699. // Generating unique vertices per face
  14700. var index;
  14701. for (index = 0; index < totalIndices; index++) {
  14702. var vertexIndex = indices[index];
  14703. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14704. kind = kinds[kindIndex];
  14705. var stride = vbs[kind].getStrideSize();
  14706. for (var offset = 0; offset < stride; offset++) {
  14707. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14708. }
  14709. }
  14710. }
  14711. // Updating faces & normal
  14712. var normals = [];
  14713. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14714. for (index = 0; index < totalIndices; index += 3) {
  14715. indices[index] = index;
  14716. indices[index + 1] = index + 1;
  14717. indices[index + 2] = index + 2;
  14718. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14719. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14720. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14721. var p1p2 = p1.subtract(p2);
  14722. var p3p2 = p3.subtract(p2);
  14723. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14724. // Store same normals for every vertex
  14725. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14726. normals.push(normal.x);
  14727. normals.push(normal.y);
  14728. normals.push(normal.z);
  14729. }
  14730. }
  14731. this.setIndices(indices);
  14732. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14733. // Updating vertex buffers
  14734. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14735. kind = kinds[kindIndex];
  14736. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14737. }
  14738. // Updating submeshes
  14739. this.releaseSubMeshes();
  14740. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14741. var previousOne = previousSubmeshes[submeshIndex];
  14742. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14743. }
  14744. this.synchronizeInstances();
  14745. };
  14746. // will inverse faces orientations, and invert normals too if specified
  14747. Mesh.prototype.flipFaces = function (flipNormals) {
  14748. if (flipNormals === void 0) { flipNormals = false; }
  14749. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14750. var i;
  14751. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14752. for (i = 0; i < vertex_data.normals.length; i++) {
  14753. vertex_data.normals[i] *= -1;
  14754. }
  14755. }
  14756. var temp;
  14757. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14758. // reassign indices
  14759. temp = vertex_data.indices[i + 1];
  14760. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14761. vertex_data.indices[i + 2] = temp;
  14762. }
  14763. vertex_data.applyToMesh(this);
  14764. };
  14765. // Instances
  14766. Mesh.prototype.createInstance = function (name) {
  14767. return new BABYLON.InstancedMesh(name, this);
  14768. };
  14769. Mesh.prototype.synchronizeInstances = function () {
  14770. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14771. var instance = this.instances[instanceIndex];
  14772. instance._syncSubMeshes();
  14773. }
  14774. };
  14775. /**
  14776. * Simplify the mesh according to the given array of settings.
  14777. * Function will return immediately and will simplify async.
  14778. * @param settings a collection of simplification settings.
  14779. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14780. * @param type the type of simplification to run.
  14781. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14782. */
  14783. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14784. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14785. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14786. this.getScene().simplificationQueue.addTask({
  14787. settings: settings,
  14788. parallelProcessing: parallelProcessing,
  14789. mesh: this,
  14790. simplificationType: simplificationType,
  14791. successCallback: successCallback
  14792. });
  14793. };
  14794. /**
  14795. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14796. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14797. * This should be used together with the simplification to avoid disappearing triangles.
  14798. * @param successCallback an optional success callback to be called after the optimization finished.
  14799. */
  14800. Mesh.prototype.optimizeIndices = function (successCallback) {
  14801. var _this = this;
  14802. var indices = this.getIndices();
  14803. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14804. var vectorPositions = [];
  14805. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14806. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14807. }
  14808. var dupes = [];
  14809. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14810. var realPos = vectorPositions.length - 1 - iteration;
  14811. var testedPosition = vectorPositions[realPos];
  14812. for (var j = 0; j < realPos; ++j) {
  14813. var againstPosition = vectorPositions[j];
  14814. if (testedPosition.equals(againstPosition)) {
  14815. dupes[realPos] = j;
  14816. break;
  14817. }
  14818. }
  14819. }, function () {
  14820. for (var i = 0; i < indices.length; ++i) {
  14821. indices[i] = dupes[indices[i]] || indices[i];
  14822. }
  14823. //indices are now reordered
  14824. var originalSubMeshes = _this.subMeshes.slice(0);
  14825. _this.setIndices(indices);
  14826. _this.subMeshes = originalSubMeshes;
  14827. if (successCallback) {
  14828. successCallback(_this);
  14829. }
  14830. });
  14831. };
  14832. // Statics
  14833. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14834. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14835. pathArray: pathArray,
  14836. closeArray: closeArray,
  14837. closePath: closePath,
  14838. offset: offset,
  14839. updatable: updatable,
  14840. sideOrientation: sideOrientation,
  14841. instance: instance
  14842. }, scene);
  14843. };
  14844. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14845. var options = {
  14846. radius: radius,
  14847. tessellation: tessellation,
  14848. sideOrientation: sideOrientation,
  14849. updatable: updatable
  14850. };
  14851. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14852. };
  14853. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14854. var options = {
  14855. size: size,
  14856. sideOrientation: sideOrientation,
  14857. updatable: updatable
  14858. };
  14859. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14860. };
  14861. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14862. var options = {
  14863. segments: segments,
  14864. diameterX: diameter,
  14865. diameterY: diameter,
  14866. diameterZ: diameter,
  14867. sideOrientation: sideOrientation,
  14868. updatable: updatable
  14869. };
  14870. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14871. };
  14872. // Cylinder and cone
  14873. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14874. var options = {
  14875. height: height,
  14876. diameterTop: diameterTop,
  14877. diameterBottom: diameterBottom,
  14878. tessellation: tessellation,
  14879. subdivisions: subdivisions,
  14880. sideOrientation: sideOrientation,
  14881. updatable: updatable
  14882. };
  14883. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14884. };
  14885. // Torus (Code from SharpDX.org)
  14886. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14887. var options = {
  14888. diameter: diameter,
  14889. thickness: thickness,
  14890. tessellation: tessellation,
  14891. sideOrientation: sideOrientation,
  14892. updatable: updatable
  14893. };
  14894. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14895. };
  14896. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14897. var options = {
  14898. radius: radius,
  14899. tube: tube,
  14900. radialSegments: radialSegments,
  14901. tubularSegments: tubularSegments,
  14902. p: p,
  14903. q: q,
  14904. sideOrientation: sideOrientation,
  14905. updatable: updatable
  14906. };
  14907. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14908. };
  14909. // Lines
  14910. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14911. var options = {
  14912. points: points,
  14913. updatable: updatable,
  14914. instance: instance
  14915. };
  14916. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14917. };
  14918. // Dashed Lines
  14919. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14920. var options = {
  14921. points: points,
  14922. dashSize: dashSize,
  14923. gapSize: gapSize,
  14924. dashNb: dashNb,
  14925. updatable: updatable
  14926. };
  14927. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14928. };
  14929. // Extrusion
  14930. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14931. var options = {
  14932. shape: shape,
  14933. path: path,
  14934. scale: scale,
  14935. rotation: rotation,
  14936. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14937. sideOrientation: sideOrientation,
  14938. instance: instance,
  14939. updatable: updatable
  14940. };
  14941. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14942. };
  14943. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14944. var options = {
  14945. shape: shape,
  14946. path: path,
  14947. scaleFunction: scaleFunction,
  14948. rotationFunction: rotationFunction,
  14949. ribbonCloseArray: ribbonCloseArray,
  14950. ribbonClosePath: ribbonClosePath,
  14951. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14952. sideOrientation: sideOrientation,
  14953. instance: instance,
  14954. updatable: updatable
  14955. };
  14956. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14957. };
  14958. // Lathe
  14959. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  14960. var options = {
  14961. shape: shape,
  14962. radius: radius,
  14963. tesselation: tessellation,
  14964. sideOrientation: sideOrientation,
  14965. updatable: updatable
  14966. };
  14967. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  14968. };
  14969. // Plane & ground
  14970. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14971. var options = {
  14972. size: size,
  14973. width: size,
  14974. height: size,
  14975. sideOrientation: sideOrientation,
  14976. updatable: updatable
  14977. };
  14978. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  14979. };
  14980. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14981. var options = {
  14982. width: width,
  14983. height: height,
  14984. subdivisions: subdivisions,
  14985. updatable: updatable
  14986. };
  14987. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  14988. };
  14989. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14990. var options = {
  14991. xmin: xmin,
  14992. zmin: zmin,
  14993. xmax: xmax,
  14994. zmax: zmax,
  14995. subdivisions: subdivisions,
  14996. precision: precision,
  14997. updatable: updatable
  14998. };
  14999. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15000. };
  15001. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15002. var options = {
  15003. width: width,
  15004. height: height,
  15005. subdivisions: subdivisions,
  15006. minHeight: minHeight,
  15007. maxHeight: maxHeight,
  15008. updatable: updatable,
  15009. onReady: onReady
  15010. };
  15011. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15012. };
  15013. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15014. var options = {
  15015. path: path,
  15016. radius: radius,
  15017. tessellation: tessellation,
  15018. radiusFunction: radiusFunction,
  15019. arc: 1,
  15020. cap: cap,
  15021. updatable: updatable,
  15022. sideOrientation: sideOrientation,
  15023. instance: instance
  15024. };
  15025. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15026. };
  15027. Mesh.CreatePolyhedron = function (name, options, scene) {
  15028. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15029. };
  15030. Mesh.CreateIcoSphere = function (name, options, scene) {
  15031. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15032. };
  15033. // Decals
  15034. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15035. var options = {
  15036. position: position,
  15037. normal: normal,
  15038. size: size,
  15039. angle: angle
  15040. };
  15041. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15042. };
  15043. // Skeletons
  15044. /**
  15045. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15046. */
  15047. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15048. var source;
  15049. if (!this._sourcePositions) {
  15050. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15051. this._sourcePositions = new Float32Array(source);
  15052. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15053. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15054. }
  15055. }
  15056. return this._sourcePositions;
  15057. };
  15058. /**
  15059. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15060. */
  15061. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15062. var source;
  15063. if (!this._sourceNormals) {
  15064. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15065. this._sourceNormals = new Float32Array(source);
  15066. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15067. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15068. }
  15069. }
  15070. return this._sourceNormals;
  15071. };
  15072. /**
  15073. * Update the vertex buffers by applying transformation from the bones
  15074. * @param {skeleton} skeleton to apply
  15075. */
  15076. Mesh.prototype.applySkeleton = function (skeleton) {
  15077. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15078. return this;
  15079. }
  15080. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15081. return this;
  15082. }
  15083. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15084. return this;
  15085. }
  15086. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15087. return this;
  15088. }
  15089. if (!this._sourcePositions) {
  15090. this.setPositionsForCPUSkinning();
  15091. }
  15092. if (!this._sourceNormals) {
  15093. this.setNormalsForCPUSkinning();
  15094. }
  15095. // positionsData checks for not being Float32Array will only pass at most once
  15096. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15097. if (!(positionsData instanceof Float32Array)) {
  15098. positionsData = new Float32Array(positionsData);
  15099. }
  15100. // normalsData checks for not being Float32Array will only pass at most once
  15101. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15102. if (!(normalsData instanceof Float32Array)) {
  15103. normalsData = new Float32Array(normalsData);
  15104. }
  15105. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15106. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15107. var skeletonMatrices = skeleton.getTransformMatrices();
  15108. var tempVector3 = BABYLON.Vector3.Zero();
  15109. var finalMatrix = new BABYLON.Matrix();
  15110. var tempMatrix = new BABYLON.Matrix();
  15111. var matWeightIdx = 0;
  15112. for (var index = 0; index < positionsData.length; index += 3) {
  15113. for (var inf = 0; inf < this.numBoneInfluencers; inf++) {
  15114. var weight = matricesWeightsData[matWeightIdx + inf];
  15115. if (weight > 0) {
  15116. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15117. finalMatrix.addToSelf(tempMatrix);
  15118. }
  15119. else
  15120. break;
  15121. }
  15122. matWeightIdx += this.numBoneInfluencers;
  15123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15124. tempVector3.toArray(positionsData, index);
  15125. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15126. tempVector3.toArray(normalsData, index);
  15127. finalMatrix.reset();
  15128. }
  15129. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15130. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15131. return this;
  15132. };
  15133. // Tools
  15134. Mesh.MinMax = function (meshes) {
  15135. var minVector = null;
  15136. var maxVector = null;
  15137. for (var i in meshes) {
  15138. var mesh = meshes[i];
  15139. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15140. if (!minVector) {
  15141. minVector = boundingBox.minimumWorld;
  15142. maxVector = boundingBox.maximumWorld;
  15143. continue;
  15144. }
  15145. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15146. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15147. }
  15148. return {
  15149. min: minVector,
  15150. max: maxVector
  15151. };
  15152. };
  15153. Mesh.Center = function (meshesOrMinMaxVector) {
  15154. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15155. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15156. };
  15157. /**
  15158. * Merge the array of meshes into a single mesh for performance reasons.
  15159. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15160. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15161. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15162. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15163. */
  15164. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15165. if (disposeSource === void 0) { disposeSource = true; }
  15166. var index;
  15167. if (!allow32BitsIndices) {
  15168. var totalVertices = 0;
  15169. // Counting vertices
  15170. for (index = 0; index < meshes.length; index++) {
  15171. if (meshes[index]) {
  15172. totalVertices += meshes[index].getTotalVertices();
  15173. if (totalVertices > 65536) {
  15174. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15175. return null;
  15176. }
  15177. }
  15178. }
  15179. }
  15180. // Merge
  15181. var vertexData;
  15182. var otherVertexData;
  15183. var source;
  15184. for (index = 0; index < meshes.length; index++) {
  15185. if (meshes[index]) {
  15186. meshes[index].computeWorldMatrix(true);
  15187. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15188. otherVertexData.transform(meshes[index].getWorldMatrix());
  15189. if (vertexData) {
  15190. vertexData.merge(otherVertexData);
  15191. }
  15192. else {
  15193. vertexData = otherVertexData;
  15194. source = meshes[index];
  15195. }
  15196. }
  15197. }
  15198. if (!meshSubclass) {
  15199. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15200. }
  15201. vertexData.applyToMesh(meshSubclass);
  15202. // Setting properties
  15203. meshSubclass.material = source.material;
  15204. meshSubclass.checkCollisions = source.checkCollisions;
  15205. // Cleaning
  15206. if (disposeSource) {
  15207. for (index = 0; index < meshes.length; index++) {
  15208. if (meshes[index]) {
  15209. meshes[index].dispose();
  15210. }
  15211. }
  15212. }
  15213. return meshSubclass;
  15214. };
  15215. // Consts
  15216. Mesh._FRONTSIDE = 0;
  15217. Mesh._BACKSIDE = 1;
  15218. Mesh._DOUBLESIDE = 2;
  15219. Mesh._DEFAULTSIDE = 0;
  15220. Mesh._NO_CAP = 0;
  15221. Mesh._CAP_START = 1;
  15222. Mesh._CAP_END = 2;
  15223. Mesh._CAP_ALL = 3;
  15224. return Mesh;
  15225. })(BABYLON.AbstractMesh);
  15226. BABYLON.Mesh = Mesh;
  15227. })(BABYLON || (BABYLON = {}));
  15228. var BABYLON;
  15229. (function (BABYLON) {
  15230. var SubMesh = (function () {
  15231. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15232. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15233. this.materialIndex = materialIndex;
  15234. this.verticesStart = verticesStart;
  15235. this.verticesCount = verticesCount;
  15236. this.indexStart = indexStart;
  15237. this.indexCount = indexCount;
  15238. this._renderId = 0;
  15239. this._mesh = mesh;
  15240. this._renderingMesh = renderingMesh || mesh;
  15241. mesh.subMeshes.push(this);
  15242. this._trianglePlanes = [];
  15243. this._id = mesh.subMeshes.length - 1;
  15244. if (createBoundingBox) {
  15245. this.refreshBoundingInfo();
  15246. mesh.computeWorldMatrix(true);
  15247. }
  15248. }
  15249. SubMesh.prototype.getBoundingInfo = function () {
  15250. return this._boundingInfo;
  15251. };
  15252. SubMesh.prototype.getMesh = function () {
  15253. return this._mesh;
  15254. };
  15255. SubMesh.prototype.getRenderingMesh = function () {
  15256. return this._renderingMesh;
  15257. };
  15258. SubMesh.prototype.getMaterial = function () {
  15259. var rootMaterial = this._renderingMesh.material;
  15260. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15261. var multiMaterial = rootMaterial;
  15262. return multiMaterial.getSubMaterial(this.materialIndex);
  15263. }
  15264. if (!rootMaterial) {
  15265. return this._mesh.getScene().defaultMaterial;
  15266. }
  15267. return rootMaterial;
  15268. };
  15269. // Methods
  15270. SubMesh.prototype.refreshBoundingInfo = function () {
  15271. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15272. if (!data) {
  15273. this._boundingInfo = this._mesh._boundingInfo;
  15274. return;
  15275. }
  15276. var indices = this._renderingMesh.getIndices();
  15277. var extend;
  15278. //is this the only submesh?
  15279. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15280. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15281. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15282. }
  15283. else {
  15284. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15285. }
  15286. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15287. };
  15288. SubMesh.prototype._checkCollision = function (collider) {
  15289. return this._boundingInfo._checkCollision(collider);
  15290. };
  15291. SubMesh.prototype.updateBoundingInfo = function (world) {
  15292. if (!this._boundingInfo) {
  15293. this.refreshBoundingInfo();
  15294. }
  15295. this._boundingInfo._update(world);
  15296. };
  15297. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15298. return this._boundingInfo.isInFrustum(frustumPlanes);
  15299. };
  15300. SubMesh.prototype.render = function (enableAlphaMode) {
  15301. this._renderingMesh.render(this, enableAlphaMode);
  15302. };
  15303. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15304. if (!this._linesIndexBuffer) {
  15305. var linesIndices = [];
  15306. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15307. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15308. }
  15309. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15310. this.linesIndexCount = linesIndices.length;
  15311. }
  15312. return this._linesIndexBuffer;
  15313. };
  15314. SubMesh.prototype.canIntersects = function (ray) {
  15315. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15316. };
  15317. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15318. var intersectInfo = null;
  15319. // Triangles test
  15320. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15321. var p0 = positions[indices[index]];
  15322. var p1 = positions[indices[index + 1]];
  15323. var p2 = positions[indices[index + 2]];
  15324. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15325. if (currentIntersectInfo) {
  15326. if (currentIntersectInfo.distance < 0) {
  15327. continue;
  15328. }
  15329. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15330. intersectInfo = currentIntersectInfo;
  15331. intersectInfo.faceId = index / 3;
  15332. if (fastCheck) {
  15333. break;
  15334. }
  15335. }
  15336. }
  15337. }
  15338. return intersectInfo;
  15339. };
  15340. // Clone
  15341. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15342. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15343. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15344. return result;
  15345. };
  15346. // Dispose
  15347. SubMesh.prototype.dispose = function () {
  15348. if (this._linesIndexBuffer) {
  15349. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15350. this._linesIndexBuffer = null;
  15351. }
  15352. // Remove from mesh
  15353. var index = this._mesh.subMeshes.indexOf(this);
  15354. this._mesh.subMeshes.splice(index, 1);
  15355. };
  15356. // Statics
  15357. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15358. var minVertexIndex = Number.MAX_VALUE;
  15359. var maxVertexIndex = -Number.MAX_VALUE;
  15360. renderingMesh = renderingMesh || mesh;
  15361. var indices = renderingMesh.getIndices();
  15362. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15363. var vertexIndex = indices[index];
  15364. if (vertexIndex < minVertexIndex)
  15365. minVertexIndex = vertexIndex;
  15366. if (vertexIndex > maxVertexIndex)
  15367. maxVertexIndex = vertexIndex;
  15368. }
  15369. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15370. };
  15371. return SubMesh;
  15372. })();
  15373. BABYLON.SubMesh = SubMesh;
  15374. })(BABYLON || (BABYLON = {}));
  15375. var BABYLON;
  15376. (function (BABYLON) {
  15377. var MeshBuilder = (function () {
  15378. function MeshBuilder() {
  15379. }
  15380. MeshBuilder.CreateBox = function (name, options, scene) {
  15381. var box = new BABYLON.Mesh(name, scene);
  15382. var vertexData = BABYLON.VertexData.CreateBox(options);
  15383. vertexData.applyToMesh(box, options.updatable);
  15384. return box;
  15385. };
  15386. MeshBuilder.CreateSphere = function (name, options, scene) {
  15387. var sphere = new BABYLON.Mesh(name, scene);
  15388. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15389. vertexData.applyToMesh(sphere, options.updatable);
  15390. return sphere;
  15391. };
  15392. MeshBuilder.CreateDisc = function (name, options, scene) {
  15393. var disc = new BABYLON.Mesh(name, scene);
  15394. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15395. vertexData.applyToMesh(disc, options.updatable);
  15396. return disc;
  15397. };
  15398. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15399. var sphere = new BABYLON.Mesh(name, scene);
  15400. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15401. vertexData.applyToMesh(sphere, options.updatable);
  15402. return sphere;
  15403. };
  15404. ;
  15405. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15406. var pathArray = options.pathArray;
  15407. var closeArray = options.closeArray;
  15408. var closePath = options.closePath;
  15409. var offset = options.offset;
  15410. var sideOrientation = options.sideOrientation;
  15411. var instance = options.instance;
  15412. var updatable = options.updatable;
  15413. if (instance) {
  15414. // positionFunction : ribbon case
  15415. // only pathArray and sideOrientation parameters are taken into account for positions update
  15416. var positionFunction = function (positions) {
  15417. var minlg = pathArray[0].length;
  15418. var i = 0;
  15419. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15420. for (var si = 1; si <= ns; si++) {
  15421. for (var p = 0; p < pathArray.length; p++) {
  15422. var path = pathArray[p];
  15423. var l = path.length;
  15424. minlg = (minlg < l) ? minlg : l;
  15425. var j = 0;
  15426. while (j < minlg) {
  15427. positions[i] = path[j].x;
  15428. positions[i + 1] = path[j].y;
  15429. positions[i + 2] = path[j].z;
  15430. j++;
  15431. i += 3;
  15432. }
  15433. if (instance._closePath) {
  15434. positions[i] = path[0].x;
  15435. positions[i + 1] = path[0].y;
  15436. positions[i + 2] = path[0].z;
  15437. i += 3;
  15438. }
  15439. }
  15440. }
  15441. };
  15442. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15443. positionFunction(positions);
  15444. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15445. if (!(instance.areNormalsFrozen)) {
  15446. var indices = instance.getIndices();
  15447. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15448. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15449. if (instance._closePath) {
  15450. var indexFirst = 0;
  15451. var indexLast = 0;
  15452. for (var p = 0; p < pathArray.length; p++) {
  15453. indexFirst = instance._idx[p] * 3;
  15454. if (p + 1 < pathArray.length) {
  15455. indexLast = (instance._idx[p + 1] - 1) * 3;
  15456. }
  15457. else {
  15458. indexLast = normals.length - 3;
  15459. }
  15460. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15461. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15462. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15463. normals[indexLast] = normals[indexFirst];
  15464. normals[indexLast + 1] = normals[indexFirst + 1];
  15465. normals[indexLast + 2] = normals[indexFirst + 2];
  15466. }
  15467. }
  15468. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15469. }
  15470. return instance;
  15471. }
  15472. else {
  15473. var ribbon = new BABYLON.Mesh(name, scene);
  15474. ribbon.sideOrientation = sideOrientation;
  15475. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15476. if (closePath) {
  15477. ribbon._idx = vertexData._idx;
  15478. }
  15479. ribbon._closePath = closePath;
  15480. ribbon._closeArray = closeArray;
  15481. vertexData.applyToMesh(ribbon, updatable);
  15482. return ribbon;
  15483. }
  15484. };
  15485. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15486. var cylinder = new BABYLON.Mesh(name, scene);
  15487. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15488. vertexData.applyToMesh(cylinder, options.updatable);
  15489. return cylinder;
  15490. };
  15491. MeshBuilder.CreateTorus = function (name, options, scene) {
  15492. var torus = new BABYLON.Mesh(name, scene);
  15493. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15494. vertexData.applyToMesh(torus, options.updatable);
  15495. return torus;
  15496. };
  15497. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15498. var torusKnot = new BABYLON.Mesh(name, scene);
  15499. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15500. vertexData.applyToMesh(torusKnot, options.updatable);
  15501. return torusKnot;
  15502. };
  15503. MeshBuilder.CreateLines = function (name, options, scene) {
  15504. var instance = options.instance;
  15505. var points = options.points;
  15506. if (instance) {
  15507. var positionFunction = function (positions) {
  15508. var i = 0;
  15509. for (var p = 0; p < points.length; p++) {
  15510. positions[i] = points[p].x;
  15511. positions[i + 1] = points[p].y;
  15512. positions[i + 2] = points[p].z;
  15513. i += 3;
  15514. }
  15515. };
  15516. instance.updateMeshPositions(positionFunction, false);
  15517. return instance;
  15518. }
  15519. // lines creation
  15520. var lines = new BABYLON.LinesMesh(name, scene);
  15521. var vertexData = BABYLON.VertexData.CreateLines(options);
  15522. vertexData.applyToMesh(lines, options.updatable);
  15523. return lines;
  15524. };
  15525. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15526. var points = options.points;
  15527. var instance = options.instance;
  15528. var gapSize = options.gapSize;
  15529. var dashNb = options.dashNb;
  15530. var dashSize = options.dashSize;
  15531. if (instance) {
  15532. var positionFunction = function (positions) {
  15533. var curvect = BABYLON.Vector3.Zero();
  15534. var nbSeg = positions.length / 6;
  15535. var lg = 0;
  15536. var nb = 0;
  15537. var shft = 0;
  15538. var dashshft = 0;
  15539. var curshft = 0;
  15540. var p = 0;
  15541. var i = 0;
  15542. var j = 0;
  15543. for (i = 0; i < points.length - 1; i++) {
  15544. points[i + 1].subtractToRef(points[i], curvect);
  15545. lg += curvect.length();
  15546. }
  15547. shft = lg / nbSeg;
  15548. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15549. for (i = 0; i < points.length - 1; i++) {
  15550. points[i + 1].subtractToRef(points[i], curvect);
  15551. nb = Math.floor(curvect.length() / shft);
  15552. curvect.normalize();
  15553. j = 0;
  15554. while (j < nb && p < positions.length) {
  15555. curshft = shft * j;
  15556. positions[p] = points[i].x + curshft * curvect.x;
  15557. positions[p + 1] = points[i].y + curshft * curvect.y;
  15558. positions[p + 2] = points[i].z + curshft * curvect.z;
  15559. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15560. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15561. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15562. p += 6;
  15563. j++;
  15564. }
  15565. }
  15566. while (p < positions.length) {
  15567. positions[p] = points[i].x;
  15568. positions[p + 1] = points[i].y;
  15569. positions[p + 2] = points[i].z;
  15570. p += 3;
  15571. }
  15572. };
  15573. instance.updateMeshPositions(positionFunction, false);
  15574. return instance;
  15575. }
  15576. // dashed lines creation
  15577. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15578. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15579. vertexData.applyToMesh(dashedLines, options.updatable);
  15580. dashedLines.dashSize = dashSize;
  15581. dashedLines.gapSize = gapSize;
  15582. return dashedLines;
  15583. };
  15584. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15585. var path = options.path;
  15586. var shape = options.shape;
  15587. var scale = options.scale || 1;
  15588. var rotation = options.rotation || 0;
  15589. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15590. var updatable = options.updatable;
  15591. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15592. var instance = options.instance;
  15593. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15594. };
  15595. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15596. var path = options.path;
  15597. var shape = options.shape;
  15598. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15599. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15600. var ribbonCloseArray = options.ribbonCloseArray || false;
  15601. var ribbonClosePath = options.ribbonClosePath || false;
  15602. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15603. var updatable = options.updatable;
  15604. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15605. var instance = options.instance;
  15606. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15607. };
  15608. MeshBuilder.CreateLathe = function (name, options, scene) {
  15609. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15610. var closed = (options.closed === undefined) ? true : options.closed;
  15611. var shape = options.shape;
  15612. var radius = options.radius || 1;
  15613. var tessellation = options.tessellation || 64;
  15614. var updatable = options.updatable;
  15615. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15616. var pi2 = Math.PI * 2;
  15617. var shapeLathe = new Array();
  15618. // first rotatable point
  15619. var i = 0;
  15620. while (shape[i].x === 0) {
  15621. i++;
  15622. }
  15623. var pt = shape[i];
  15624. for (i = 0; i < shape.length; i++) {
  15625. shapeLathe.push(shape[i].subtract(pt));
  15626. }
  15627. // circle path
  15628. var step = pi2 / tessellation * arc;
  15629. var rotated;
  15630. var path = new Array();
  15631. ;
  15632. for (i = 0; i <= tessellation; i++) {
  15633. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15634. path.push(rotated);
  15635. }
  15636. if (closed) {
  15637. path.push(path[0]);
  15638. }
  15639. // extrusion
  15640. var scaleFunction = function () { return 1; };
  15641. var rotateFunction = function () { return 0; };
  15642. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15643. return lathe;
  15644. };
  15645. MeshBuilder.CreatePlane = function (name, options, scene) {
  15646. var plane = new BABYLON.Mesh(name, scene);
  15647. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15648. vertexData.applyToMesh(plane, options.updatable);
  15649. if (options.sourcePlane) {
  15650. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15651. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15652. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15653. plane.rotate(vectorProduct, product);
  15654. }
  15655. return plane;
  15656. };
  15657. MeshBuilder.CreateGround = function (name, options, scene) {
  15658. var ground = new BABYLON.GroundMesh(name, scene);
  15659. ground._setReady(false);
  15660. ground._subdivisions = options.subdivisions || 1;
  15661. var vertexData = BABYLON.VertexData.CreateGround(options);
  15662. vertexData.applyToMesh(ground, options.updatable);
  15663. ground._setReady(true);
  15664. return ground;
  15665. };
  15666. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15667. var tiledGround = new BABYLON.Mesh(name, scene);
  15668. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15669. vertexData.applyToMesh(tiledGround, options.updatable);
  15670. return tiledGround;
  15671. };
  15672. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15673. var width = options.width || 10;
  15674. var height = options.height || 10;
  15675. var subdivisions = options.subdivisions || 1;
  15676. var minHeight = options.minHeight;
  15677. var maxHeight = options.maxHeight || 10;
  15678. var updatable = options.updatable;
  15679. var onReady = options.onReady;
  15680. var ground = new BABYLON.GroundMesh(name, scene);
  15681. ground._subdivisions = subdivisions;
  15682. ground._setReady(false);
  15683. var onload = function (img) {
  15684. // Getting height map data
  15685. var canvas = document.createElement("canvas");
  15686. var context = canvas.getContext("2d");
  15687. var bufferWidth = img.width;
  15688. var bufferHeight = img.height;
  15689. canvas.width = bufferWidth;
  15690. canvas.height = bufferHeight;
  15691. context.drawImage(img, 0, 0);
  15692. // Create VertexData from map data
  15693. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15694. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15695. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15696. width: width, height: height,
  15697. subdivisions: subdivisions,
  15698. minHeight: minHeight, maxHeight: maxHeight,
  15699. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15700. });
  15701. vertexData.applyToMesh(ground, updatable);
  15702. ground._setReady(true);
  15703. //execute ready callback, if set
  15704. if (onReady) {
  15705. onReady(ground);
  15706. }
  15707. };
  15708. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15709. return ground;
  15710. };
  15711. MeshBuilder.CreateTube = function (name, options, scene) {
  15712. var path = options.path;
  15713. var radius = options.radius || 1;
  15714. var tessellation = options.tessellation || 64;
  15715. var radiusFunction = options.radiusFunction;
  15716. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15717. var updatable = options.updatable;
  15718. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15719. var instance = options.instance;
  15720. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15721. // tube geometry
  15722. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15723. var tangents = path3D.getTangents();
  15724. var normals = path3D.getNormals();
  15725. var distances = path3D.getDistances();
  15726. var pi2 = Math.PI * 2;
  15727. var step = pi2 / tessellation * arc;
  15728. var returnRadius = function () { return radius; };
  15729. var radiusFunctionFinal = radiusFunction || returnRadius;
  15730. var circlePath;
  15731. var rad;
  15732. var normal;
  15733. var rotated;
  15734. var rotationMatrix = BABYLON.Matrix.Zero();
  15735. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15736. for (var i = 0; i < path.length; i++) {
  15737. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15738. circlePath = Array(); // current circle array
  15739. normal = normals[i]; // current normal
  15740. for (var t = 0; t < tessellation; t++) {
  15741. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15742. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15743. circlePath.push(rotated);
  15744. }
  15745. circlePaths[index] = circlePath;
  15746. index++;
  15747. }
  15748. // cap
  15749. var capPath = function (nbPoints, pathIndex) {
  15750. var pointCap = Array();
  15751. for (var i = 0; i < nbPoints; i++) {
  15752. pointCap.push(path[pathIndex]);
  15753. }
  15754. return pointCap;
  15755. };
  15756. switch (cap) {
  15757. case BABYLON.Mesh.NO_CAP:
  15758. break;
  15759. case BABYLON.Mesh.CAP_START:
  15760. circlePaths[0] = capPath(tessellation, 0);
  15761. circlePaths[1] = circlePaths[2].slice(0);
  15762. break;
  15763. case BABYLON.Mesh.CAP_END:
  15764. circlePaths[index] = circlePaths[index - 1].slice(0);
  15765. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15766. break;
  15767. case BABYLON.Mesh.CAP_ALL:
  15768. circlePaths[0] = capPath(tessellation, 0);
  15769. circlePaths[1] = circlePaths[2].slice(0);
  15770. circlePaths[index] = circlePaths[index - 1].slice(0);
  15771. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15772. break;
  15773. default:
  15774. break;
  15775. }
  15776. return circlePaths;
  15777. };
  15778. var path3D;
  15779. var pathArray;
  15780. if (instance) {
  15781. var arc = options.arc || instance.arc;
  15782. path3D = (instance.path3D).update(path);
  15783. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15784. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15785. instance.path3D = path3D;
  15786. instance.pathArray = pathArray;
  15787. instance.arc = arc;
  15788. return instance;
  15789. }
  15790. // tube creation
  15791. path3D = new BABYLON.Path3D(path);
  15792. var newPathArray = new Array();
  15793. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15794. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15795. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15796. tube.pathArray = pathArray;
  15797. tube.path3D = path3D;
  15798. tube.tessellation = tessellation;
  15799. tube.cap = cap;
  15800. tube.arc = options.arc;
  15801. return tube;
  15802. };
  15803. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15804. var polyhedron = new BABYLON.Mesh(name, scene);
  15805. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15806. vertexData.applyToMesh(polyhedron, options.updatable);
  15807. return polyhedron;
  15808. };
  15809. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15810. var indices = sourceMesh.getIndices();
  15811. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15812. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15813. var position = options.position || BABYLON.Vector3.Zero();
  15814. var normal = options.normal || BABYLON.Vector3.Up();
  15815. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15816. var angle = options.angle || 0;
  15817. // Getting correct rotation
  15818. if (!normal) {
  15819. var target = new BABYLON.Vector3(0, 0, 1);
  15820. var camera = sourceMesh.getScene().activeCamera;
  15821. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15822. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15823. }
  15824. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15825. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15826. var pitch = Math.atan2(normal.y, len);
  15827. // Matrix
  15828. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15829. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15830. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15831. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15832. var vertexData = new BABYLON.VertexData();
  15833. vertexData.indices = [];
  15834. vertexData.positions = [];
  15835. vertexData.normals = [];
  15836. vertexData.uvs = [];
  15837. var currentVertexDataIndex = 0;
  15838. var extractDecalVector3 = function (indexId) {
  15839. var vertexId = indices[indexId];
  15840. var result = new BABYLON.PositionNormalVertex();
  15841. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15842. // Send vector to decal local world
  15843. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15844. // Get normal
  15845. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15846. return result;
  15847. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15848. var clip = function (vertices, axis) {
  15849. if (vertices.length === 0) {
  15850. return vertices;
  15851. }
  15852. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15853. var clipVertices = function (v0, v1) {
  15854. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15855. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15856. };
  15857. var result = new Array();
  15858. for (var index = 0; index < vertices.length; index += 3) {
  15859. var v1Out;
  15860. var v2Out;
  15861. var v3Out;
  15862. var total = 0;
  15863. var nV1, nV2, nV3, nV4;
  15864. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15865. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15866. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15867. v1Out = d1 > 0;
  15868. v2Out = d2 > 0;
  15869. v3Out = d3 > 0;
  15870. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15871. switch (total) {
  15872. case 0:
  15873. result.push(vertices[index]);
  15874. result.push(vertices[index + 1]);
  15875. result.push(vertices[index + 2]);
  15876. break;
  15877. case 1:
  15878. if (v1Out) {
  15879. nV1 = vertices[index + 1];
  15880. nV2 = vertices[index + 2];
  15881. nV3 = clipVertices(vertices[index], nV1);
  15882. nV4 = clipVertices(vertices[index], nV2);
  15883. }
  15884. if (v2Out) {
  15885. nV1 = vertices[index];
  15886. nV2 = vertices[index + 2];
  15887. nV3 = clipVertices(vertices[index + 1], nV1);
  15888. nV4 = clipVertices(vertices[index + 1], nV2);
  15889. result.push(nV3);
  15890. result.push(nV2.clone());
  15891. result.push(nV1.clone());
  15892. result.push(nV2.clone());
  15893. result.push(nV3.clone());
  15894. result.push(nV4);
  15895. break;
  15896. }
  15897. if (v3Out) {
  15898. nV1 = vertices[index];
  15899. nV2 = vertices[index + 1];
  15900. nV3 = clipVertices(vertices[index + 2], nV1);
  15901. nV4 = clipVertices(vertices[index + 2], nV2);
  15902. }
  15903. result.push(nV1.clone());
  15904. result.push(nV2.clone());
  15905. result.push(nV3);
  15906. result.push(nV4);
  15907. result.push(nV3.clone());
  15908. result.push(nV2.clone());
  15909. break;
  15910. case 2:
  15911. if (!v1Out) {
  15912. nV1 = vertices[index].clone();
  15913. nV2 = clipVertices(nV1, vertices[index + 1]);
  15914. nV3 = clipVertices(nV1, vertices[index + 2]);
  15915. result.push(nV1);
  15916. result.push(nV2);
  15917. result.push(nV3);
  15918. }
  15919. if (!v2Out) {
  15920. nV1 = vertices[index + 1].clone();
  15921. nV2 = clipVertices(nV1, vertices[index + 2]);
  15922. nV3 = clipVertices(nV1, vertices[index]);
  15923. result.push(nV1);
  15924. result.push(nV2);
  15925. result.push(nV3);
  15926. }
  15927. if (!v3Out) {
  15928. nV1 = vertices[index + 2].clone();
  15929. nV2 = clipVertices(nV1, vertices[index]);
  15930. nV3 = clipVertices(nV1, vertices[index + 1]);
  15931. result.push(nV1);
  15932. result.push(nV2);
  15933. result.push(nV3);
  15934. }
  15935. break;
  15936. case 3:
  15937. break;
  15938. }
  15939. }
  15940. return result;
  15941. };
  15942. for (var index = 0; index < indices.length; index += 3) {
  15943. var faceVertices = new Array();
  15944. faceVertices.push(extractDecalVector3(index));
  15945. faceVertices.push(extractDecalVector3(index + 1));
  15946. faceVertices.push(extractDecalVector3(index + 2));
  15947. // Clip
  15948. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15949. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15950. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15951. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15952. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15953. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15954. if (faceVertices.length === 0) {
  15955. continue;
  15956. }
  15957. // Add UVs and get back to world
  15958. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15959. var vertex = faceVertices[vIndex];
  15960. vertexData.indices.push(currentVertexDataIndex);
  15961. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15962. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15963. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15964. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15965. currentVertexDataIndex++;
  15966. }
  15967. }
  15968. // Return mesh
  15969. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  15970. vertexData.applyToMesh(decal);
  15971. decal.position = position.clone();
  15972. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15973. return decal;
  15974. };
  15975. // Privates
  15976. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15977. // extrusion geometry
  15978. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15979. var tangents = path3D.getTangents();
  15980. var normals = path3D.getNormals();
  15981. var binormals = path3D.getBinormals();
  15982. var distances = path3D.getDistances();
  15983. var angle = 0;
  15984. var returnScale = function () { return scale; };
  15985. var returnRotation = function () { return rotation; };
  15986. var rotate = custom ? rotateFunction : returnRotation;
  15987. var scl = custom ? scaleFunction : returnScale;
  15988. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15989. var rotationMatrix = BABYLON.Matrix.Zero();
  15990. for (var i = 0; i < curve.length; i++) {
  15991. var shapePath = new Array();
  15992. var angleStep = rotate(i, distances[i]);
  15993. var scaleRatio = scl(i, distances[i]);
  15994. for (var p = 0; p < shape.length; p++) {
  15995. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  15996. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15997. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15998. shapePath.push(rotated);
  15999. }
  16000. shapePaths[index] = shapePath;
  16001. angle += angleStep;
  16002. index++;
  16003. }
  16004. // cap
  16005. var capPath = function (shapePath) {
  16006. var pointCap = Array();
  16007. var barycenter = BABYLON.Vector3.Zero();
  16008. var i;
  16009. for (i = 0; i < shapePath.length; i++) {
  16010. barycenter.addInPlace(shapePath[i]);
  16011. }
  16012. barycenter.scaleInPlace(1 / shapePath.length);
  16013. for (i = 0; i < shapePath.length; i++) {
  16014. pointCap.push(barycenter);
  16015. }
  16016. return pointCap;
  16017. };
  16018. switch (cap) {
  16019. case BABYLON.Mesh.NO_CAP:
  16020. break;
  16021. case BABYLON.Mesh.CAP_START:
  16022. shapePaths[0] = capPath(shapePaths[2]);
  16023. shapePaths[1] = shapePaths[2].slice(0);
  16024. break;
  16025. case BABYLON.Mesh.CAP_END:
  16026. shapePaths[index] = shapePaths[index - 1];
  16027. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16028. break;
  16029. case BABYLON.Mesh.CAP_ALL:
  16030. shapePaths[0] = capPath(shapePaths[2]);
  16031. shapePaths[1] = shapePaths[2].slice(0);
  16032. shapePaths[index] = shapePaths[index - 1];
  16033. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16034. break;
  16035. default:
  16036. break;
  16037. }
  16038. return shapePaths;
  16039. };
  16040. var path3D;
  16041. var pathArray;
  16042. if (instance) {
  16043. path3D = (instance.path3D).update(curve);
  16044. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16045. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16046. return instance;
  16047. }
  16048. // extruded shape creation
  16049. path3D = new BABYLON.Path3D(curve);
  16050. var newShapePaths = new Array();
  16051. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16052. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16053. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16054. extrudedGeneric.pathArray = pathArray;
  16055. extrudedGeneric.path3D = path3D;
  16056. extrudedGeneric.cap = cap;
  16057. return extrudedGeneric;
  16058. };
  16059. return MeshBuilder;
  16060. })();
  16061. BABYLON.MeshBuilder = MeshBuilder;
  16062. })(BABYLON || (BABYLON = {}));
  16063. var BABYLON;
  16064. (function (BABYLON) {
  16065. var BaseTexture = (function () {
  16066. function BaseTexture(scene) {
  16067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16068. this.hasAlpha = false;
  16069. this.getAlphaFromRGB = false;
  16070. this.level = 1;
  16071. this.isCube = false;
  16072. this.isRenderTarget = false;
  16073. this.animations = new Array();
  16074. this.coordinatesIndex = 0;
  16075. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16076. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16077. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16078. this.anisotropicFilteringLevel = 4;
  16079. this._scene = scene;
  16080. this._scene.textures.push(this);
  16081. }
  16082. BaseTexture.prototype.getScene = function () {
  16083. return this._scene;
  16084. };
  16085. BaseTexture.prototype.getTextureMatrix = function () {
  16086. return null;
  16087. };
  16088. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16089. return null;
  16090. };
  16091. BaseTexture.prototype.getInternalTexture = function () {
  16092. return this._texture;
  16093. };
  16094. BaseTexture.prototype.isReady = function () {
  16095. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16096. return true;
  16097. }
  16098. if (this._texture) {
  16099. return this._texture.isReady;
  16100. }
  16101. return false;
  16102. };
  16103. BaseTexture.prototype.getSize = function () {
  16104. if (this._texture._width) {
  16105. return { width: this._texture._width, height: this._texture._height };
  16106. }
  16107. if (this._texture._size) {
  16108. return { width: this._texture._size, height: this._texture._size };
  16109. }
  16110. return { width: 0, height: 0 };
  16111. };
  16112. BaseTexture.prototype.getBaseSize = function () {
  16113. if (!this.isReady())
  16114. return { width: 0, height: 0 };
  16115. if (this._texture._size) {
  16116. return { width: this._texture._size, height: this._texture._size };
  16117. }
  16118. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16119. };
  16120. BaseTexture.prototype.scale = function (ratio) {
  16121. };
  16122. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16123. get: function () {
  16124. return false;
  16125. },
  16126. enumerable: true,
  16127. configurable: true
  16128. });
  16129. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16130. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16131. for (var index = 0; index < texturesCache.length; index++) {
  16132. var texturesCacheEntry = texturesCache[index];
  16133. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16134. texturesCache.splice(index, 1);
  16135. return;
  16136. }
  16137. }
  16138. };
  16139. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16140. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16141. for (var index = 0; index < texturesCache.length; index++) {
  16142. var texturesCacheEntry = texturesCache[index];
  16143. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16144. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16145. texturesCacheEntry.references++;
  16146. return texturesCacheEntry;
  16147. }
  16148. }
  16149. }
  16150. return null;
  16151. };
  16152. BaseTexture.prototype.delayLoad = function () {
  16153. };
  16154. BaseTexture.prototype.clone = function () {
  16155. return null;
  16156. };
  16157. BaseTexture.prototype.releaseInternalTexture = function () {
  16158. if (this._texture) {
  16159. this._scene.getEngine().releaseInternalTexture(this._texture);
  16160. delete this._texture;
  16161. }
  16162. };
  16163. BaseTexture.prototype.dispose = function () {
  16164. // Animations
  16165. this.getScene().stopAnimation(this);
  16166. // Remove from scene
  16167. var index = this._scene.textures.indexOf(this);
  16168. if (index >= 0) {
  16169. this._scene.textures.splice(index, 1);
  16170. }
  16171. if (this._texture === undefined) {
  16172. return;
  16173. }
  16174. // Callback
  16175. if (this.onDispose) {
  16176. this.onDispose();
  16177. }
  16178. };
  16179. return BaseTexture;
  16180. })();
  16181. BABYLON.BaseTexture = BaseTexture;
  16182. })(BABYLON || (BABYLON = {}));
  16183. var BABYLON;
  16184. (function (BABYLON) {
  16185. var Texture = (function (_super) {
  16186. __extends(Texture, _super);
  16187. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16188. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16189. if (onLoad === void 0) { onLoad = null; }
  16190. if (onError === void 0) { onError = null; }
  16191. if (buffer === void 0) { buffer = null; }
  16192. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16193. _super.call(this, scene);
  16194. this.uOffset = 0;
  16195. this.vOffset = 0;
  16196. this.uScale = 1.0;
  16197. this.vScale = 1.0;
  16198. this.uAng = 0;
  16199. this.vAng = 0;
  16200. this.wAng = 0;
  16201. this.name = url;
  16202. this.url = url;
  16203. this._noMipmap = noMipmap;
  16204. this._invertY = invertY;
  16205. this._samplingMode = samplingMode;
  16206. this._buffer = buffer;
  16207. this._deleteBuffer = deleteBuffer;
  16208. if (!url) {
  16209. return;
  16210. }
  16211. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16212. if (!this._texture) {
  16213. if (!scene.useDelayedTextureLoading) {
  16214. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16215. if (deleteBuffer) {
  16216. delete this._buffer;
  16217. }
  16218. }
  16219. else {
  16220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16221. }
  16222. }
  16223. else {
  16224. BABYLON.Tools.SetImmediate(function () {
  16225. if (onLoad) {
  16226. onLoad();
  16227. }
  16228. });
  16229. }
  16230. }
  16231. Texture.prototype.delayLoad = function () {
  16232. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16233. return;
  16234. }
  16235. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16236. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16237. if (!this._texture) {
  16238. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16239. if (this._deleteBuffer) {
  16240. delete this._buffer;
  16241. }
  16242. }
  16243. };
  16244. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16245. if (!this._texture) {
  16246. return;
  16247. }
  16248. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16249. };
  16250. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16251. x *= this.uScale;
  16252. y *= this.vScale;
  16253. x -= 0.5 * this.uScale;
  16254. y -= 0.5 * this.vScale;
  16255. z -= 0.5;
  16256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16257. t.x += 0.5 * this.uScale + this.uOffset;
  16258. t.y += 0.5 * this.vScale + this.vOffset;
  16259. t.z += 0.5;
  16260. };
  16261. Texture.prototype.getTextureMatrix = function () {
  16262. if (this.uOffset === this._cachedUOffset &&
  16263. this.vOffset === this._cachedVOffset &&
  16264. this.uScale === this._cachedUScale &&
  16265. this.vScale === this._cachedVScale &&
  16266. this.uAng === this._cachedUAng &&
  16267. this.vAng === this._cachedVAng &&
  16268. this.wAng === this._cachedWAng) {
  16269. return this._cachedTextureMatrix;
  16270. }
  16271. this._cachedUOffset = this.uOffset;
  16272. this._cachedVOffset = this.vOffset;
  16273. this._cachedUScale = this.uScale;
  16274. this._cachedVScale = this.vScale;
  16275. this._cachedUAng = this.uAng;
  16276. this._cachedVAng = this.vAng;
  16277. this._cachedWAng = this.wAng;
  16278. if (!this._cachedTextureMatrix) {
  16279. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16280. this._rowGenerationMatrix = new BABYLON.Matrix();
  16281. this._t0 = BABYLON.Vector3.Zero();
  16282. this._t1 = BABYLON.Vector3.Zero();
  16283. this._t2 = BABYLON.Vector3.Zero();
  16284. }
  16285. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16286. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16287. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16288. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16289. this._t1.subtractInPlace(this._t0);
  16290. this._t2.subtractInPlace(this._t0);
  16291. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16292. this._cachedTextureMatrix.m[0] = this._t1.x;
  16293. this._cachedTextureMatrix.m[1] = this._t1.y;
  16294. this._cachedTextureMatrix.m[2] = this._t1.z;
  16295. this._cachedTextureMatrix.m[4] = this._t2.x;
  16296. this._cachedTextureMatrix.m[5] = this._t2.y;
  16297. this._cachedTextureMatrix.m[6] = this._t2.z;
  16298. this._cachedTextureMatrix.m[8] = this._t0.x;
  16299. this._cachedTextureMatrix.m[9] = this._t0.y;
  16300. this._cachedTextureMatrix.m[10] = this._t0.z;
  16301. return this._cachedTextureMatrix;
  16302. };
  16303. Texture.prototype.getReflectionTextureMatrix = function () {
  16304. if (this.uOffset === this._cachedUOffset &&
  16305. this.vOffset === this._cachedVOffset &&
  16306. this.uScale === this._cachedUScale &&
  16307. this.vScale === this._cachedVScale &&
  16308. this.coordinatesMode === this._cachedCoordinatesMode) {
  16309. return this._cachedTextureMatrix;
  16310. }
  16311. if (!this._cachedTextureMatrix) {
  16312. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16313. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16314. }
  16315. this._cachedCoordinatesMode = this.coordinatesMode;
  16316. switch (this.coordinatesMode) {
  16317. case Texture.PLANAR_MODE:
  16318. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16319. this._cachedTextureMatrix[0] = this.uScale;
  16320. this._cachedTextureMatrix[5] = this.vScale;
  16321. this._cachedTextureMatrix[12] = this.uOffset;
  16322. this._cachedTextureMatrix[13] = this.vOffset;
  16323. break;
  16324. case Texture.PROJECTION_MODE:
  16325. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16326. this._projectionModeMatrix.m[0] = 0.5;
  16327. this._projectionModeMatrix.m[5] = -0.5;
  16328. this._projectionModeMatrix.m[10] = 0.0;
  16329. this._projectionModeMatrix.m[12] = 0.5;
  16330. this._projectionModeMatrix.m[13] = 0.5;
  16331. this._projectionModeMatrix.m[14] = 1.0;
  16332. this._projectionModeMatrix.m[15] = 1.0;
  16333. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16334. break;
  16335. default:
  16336. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16337. break;
  16338. }
  16339. return this._cachedTextureMatrix;
  16340. };
  16341. Texture.prototype.clone = function () {
  16342. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16343. // Base texture
  16344. newTexture.hasAlpha = this.hasAlpha;
  16345. newTexture.level = this.level;
  16346. newTexture.wrapU = this.wrapU;
  16347. newTexture.wrapV = this.wrapV;
  16348. newTexture.coordinatesIndex = this.coordinatesIndex;
  16349. newTexture.coordinatesMode = this.coordinatesMode;
  16350. // Texture
  16351. newTexture.uOffset = this.uOffset;
  16352. newTexture.vOffset = this.vOffset;
  16353. newTexture.uScale = this.uScale;
  16354. newTexture.vScale = this.vScale;
  16355. newTexture.uAng = this.uAng;
  16356. newTexture.vAng = this.vAng;
  16357. newTexture.wAng = this.wAng;
  16358. return newTexture;
  16359. };
  16360. // Statics
  16361. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16362. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16363. if (onLoad === void 0) { onLoad = null; }
  16364. if (onError === void 0) { onError = null; }
  16365. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16366. };
  16367. // Constants
  16368. Texture.NEAREST_SAMPLINGMODE = 1;
  16369. Texture.BILINEAR_SAMPLINGMODE = 2;
  16370. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16371. Texture.EXPLICIT_MODE = 0;
  16372. Texture.SPHERICAL_MODE = 1;
  16373. Texture.PLANAR_MODE = 2;
  16374. Texture.CUBIC_MODE = 3;
  16375. Texture.PROJECTION_MODE = 4;
  16376. Texture.SKYBOX_MODE = 5;
  16377. Texture.INVCUBIC_MODE = 6;
  16378. Texture.EQUIRECTANGULAR_MODE = 7;
  16379. Texture.CLAMP_ADDRESSMODE = 0;
  16380. Texture.WRAP_ADDRESSMODE = 1;
  16381. Texture.MIRROR_ADDRESSMODE = 2;
  16382. return Texture;
  16383. })(BABYLON.BaseTexture);
  16384. BABYLON.Texture = Texture;
  16385. })(BABYLON || (BABYLON = {}));
  16386. var BABYLON;
  16387. (function (BABYLON) {
  16388. var CubeTexture = (function (_super) {
  16389. __extends(CubeTexture, _super);
  16390. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16391. _super.call(this, scene);
  16392. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16393. this.name = rootUrl;
  16394. this.url = rootUrl;
  16395. this._noMipmap = noMipmap;
  16396. this.hasAlpha = false;
  16397. if (!rootUrl) {
  16398. return;
  16399. }
  16400. this._texture = this._getFromCache(rootUrl, noMipmap);
  16401. if (!extensions) {
  16402. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16403. }
  16404. this._extensions = extensions;
  16405. if (!this._texture) {
  16406. if (!scene.useDelayedTextureLoading) {
  16407. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16408. }
  16409. else {
  16410. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16411. }
  16412. }
  16413. this.isCube = true;
  16414. this._textureMatrix = BABYLON.Matrix.Identity();
  16415. }
  16416. CubeTexture.prototype.clone = function () {
  16417. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16418. // Base texture
  16419. newTexture.level = this.level;
  16420. newTexture.wrapU = this.wrapU;
  16421. newTexture.wrapV = this.wrapV;
  16422. newTexture.coordinatesIndex = this.coordinatesIndex;
  16423. newTexture.coordinatesMode = this.coordinatesMode;
  16424. return newTexture;
  16425. };
  16426. // Methods
  16427. CubeTexture.prototype.delayLoad = function () {
  16428. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16429. return;
  16430. }
  16431. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16432. this._texture = this._getFromCache(this.url, this._noMipmap);
  16433. if (!this._texture) {
  16434. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16435. }
  16436. };
  16437. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16438. return this._textureMatrix;
  16439. };
  16440. return CubeTexture;
  16441. })(BABYLON.BaseTexture);
  16442. BABYLON.CubeTexture = CubeTexture;
  16443. })(BABYLON || (BABYLON = {}));
  16444. var BABYLON;
  16445. (function (BABYLON) {
  16446. var RenderTargetTexture = (function (_super) {
  16447. __extends(RenderTargetTexture, _super);
  16448. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16449. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16450. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16451. if (isCube === void 0) { isCube = false; }
  16452. _super.call(this, null, scene, !generateMipMaps);
  16453. this.isCube = isCube;
  16454. this.renderList = new Array();
  16455. this.renderParticles = true;
  16456. this.renderSprites = false;
  16457. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16458. this._currentRefreshId = -1;
  16459. this._refreshRate = 1;
  16460. this.name = name;
  16461. this.isRenderTarget = true;
  16462. this._size = size;
  16463. this._generateMipMaps = generateMipMaps;
  16464. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16465. if (isCube) {
  16466. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16467. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16468. this._textureMatrix = BABYLON.Matrix.Identity();
  16469. }
  16470. else {
  16471. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16472. }
  16473. // Rendering groups
  16474. this._renderingManager = new BABYLON.RenderingManager(scene);
  16475. }
  16476. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16477. get: function () {
  16478. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16479. },
  16480. enumerable: true,
  16481. configurable: true
  16482. });
  16483. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16484. get: function () {
  16485. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16491. get: function () {
  16492. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16498. this._currentRefreshId = -1;
  16499. };
  16500. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16501. get: function () {
  16502. return this._refreshRate;
  16503. },
  16504. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16505. set: function (value) {
  16506. this._refreshRate = value;
  16507. this.resetRefreshCounter();
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. RenderTargetTexture.prototype._shouldRender = function () {
  16513. if (this._currentRefreshId === -1) {
  16514. this._currentRefreshId = 1;
  16515. return true;
  16516. }
  16517. if (this.refreshRate === this._currentRefreshId) {
  16518. this._currentRefreshId = 1;
  16519. return true;
  16520. }
  16521. this._currentRefreshId++;
  16522. return false;
  16523. };
  16524. RenderTargetTexture.prototype.isReady = function () {
  16525. if (!this.getScene().renderTargetsEnabled) {
  16526. return false;
  16527. }
  16528. return _super.prototype.isReady.call(this);
  16529. };
  16530. RenderTargetTexture.prototype.getRenderSize = function () {
  16531. return this._size;
  16532. };
  16533. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16534. get: function () {
  16535. return true;
  16536. },
  16537. enumerable: true,
  16538. configurable: true
  16539. });
  16540. RenderTargetTexture.prototype.scale = function (ratio) {
  16541. var newSize = this._size * ratio;
  16542. this.resize(newSize, this._generateMipMaps);
  16543. };
  16544. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16545. if (this.isCube) {
  16546. return this._textureMatrix;
  16547. }
  16548. return _super.prototype.getReflectionTextureMatrix.call(this);
  16549. };
  16550. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16551. this.releaseInternalTexture();
  16552. if (this.isCube) {
  16553. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16554. }
  16555. else {
  16556. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16557. }
  16558. };
  16559. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16560. var scene = this.getScene();
  16561. if (this._waitingRenderList) {
  16562. this.renderList = [];
  16563. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16564. var id = this._waitingRenderList[index];
  16565. this.renderList.push(scene.getMeshByID(id));
  16566. }
  16567. delete this._waitingRenderList;
  16568. }
  16569. if (this.renderList && this.renderList.length === 0) {
  16570. return;
  16571. }
  16572. // Prepare renderingManager
  16573. this._renderingManager.reset();
  16574. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16575. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16576. var mesh = currentRenderList[meshIndex];
  16577. if (mesh) {
  16578. if (!mesh.isReady()) {
  16579. // Reset _currentRefreshId
  16580. this.resetRefreshCounter();
  16581. continue;
  16582. }
  16583. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16584. mesh._activate(scene.getRenderId());
  16585. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16586. var subMesh = mesh.subMeshes[subIndex];
  16587. scene._activeIndices += subMesh.indexCount;
  16588. this._renderingManager.dispatch(subMesh);
  16589. }
  16590. }
  16591. }
  16592. }
  16593. if (this.isCube) {
  16594. for (var face = 0; face < 6; face++) {
  16595. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16596. }
  16597. }
  16598. else {
  16599. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16600. }
  16601. if (this.onAfterUnbind) {
  16602. this.onAfterUnbind();
  16603. }
  16604. scene.resetCachedMaterial();
  16605. };
  16606. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16607. var scene = this.getScene();
  16608. var engine = scene.getEngine();
  16609. // Bind
  16610. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16611. if (this.isCube) {
  16612. engine.bindFramebuffer(this._texture, faceIndex);
  16613. }
  16614. else {
  16615. engine.bindFramebuffer(this._texture);
  16616. }
  16617. }
  16618. if (this.onBeforeRender) {
  16619. this.onBeforeRender(faceIndex);
  16620. }
  16621. // Clear
  16622. if (this.onClear) {
  16623. this.onClear(engine);
  16624. }
  16625. else {
  16626. engine.clear(scene.clearColor, true, true);
  16627. }
  16628. if (!this._doNotChangeAspectRatio) {
  16629. scene.updateTransformMatrix(true);
  16630. }
  16631. // Render
  16632. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16633. if (useCameraPostProcess) {
  16634. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16635. }
  16636. if (!this._doNotChangeAspectRatio) {
  16637. scene.updateTransformMatrix(true);
  16638. }
  16639. if (this.onAfterRender) {
  16640. this.onAfterRender(faceIndex);
  16641. }
  16642. // Dump ?
  16643. if (dumpForDebug) {
  16644. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16645. }
  16646. // Unbind
  16647. if (!this.isCube || faceIndex === 5) {
  16648. if (this.isCube) {
  16649. if (faceIndex === 5) {
  16650. engine.generateMipMapsForCubemap(this._texture);
  16651. }
  16652. }
  16653. engine.unBindFramebuffer(this._texture, this.isCube);
  16654. }
  16655. };
  16656. RenderTargetTexture.prototype.clone = function () {
  16657. var textureSize = this.getSize();
  16658. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16659. // Base texture
  16660. newTexture.hasAlpha = this.hasAlpha;
  16661. newTexture.level = this.level;
  16662. // RenderTarget Texture
  16663. newTexture.coordinatesMode = this.coordinatesMode;
  16664. newTexture.renderList = this.renderList.slice(0);
  16665. return newTexture;
  16666. };
  16667. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16668. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16669. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16670. return RenderTargetTexture;
  16671. })(BABYLON.Texture);
  16672. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16673. })(BABYLON || (BABYLON = {}));
  16674. var BABYLON;
  16675. (function (BABYLON) {
  16676. var ProceduralTexture = (function (_super) {
  16677. __extends(ProceduralTexture, _super);
  16678. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16680. _super.call(this, null, scene, !generateMipMaps);
  16681. this.isEnabled = true;
  16682. this._currentRefreshId = -1;
  16683. this._refreshRate = 1;
  16684. this._vertexDeclaration = [2];
  16685. this._vertexStrideSize = 2 * 4;
  16686. this._uniforms = new Array();
  16687. this._samplers = new Array();
  16688. this._textures = new Array();
  16689. this._floats = new Array();
  16690. this._floatsArrays = {};
  16691. this._colors3 = new Array();
  16692. this._colors4 = new Array();
  16693. this._vectors2 = new Array();
  16694. this._vectors3 = new Array();
  16695. this._matrices = new Array();
  16696. this._fallbackTextureUsed = false;
  16697. scene._proceduralTextures.push(this);
  16698. this.name = name;
  16699. this.isRenderTarget = true;
  16700. this._size = size;
  16701. this._generateMipMaps = generateMipMaps;
  16702. this.setFragment(fragment);
  16703. this._fallbackTexture = fallbackTexture;
  16704. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16705. // VBO
  16706. var vertices = [];
  16707. vertices.push(1, 1);
  16708. vertices.push(-1, 1);
  16709. vertices.push(-1, -1);
  16710. vertices.push(1, -1);
  16711. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16712. // Indices
  16713. var indices = [];
  16714. indices.push(0);
  16715. indices.push(1);
  16716. indices.push(2);
  16717. indices.push(0);
  16718. indices.push(2);
  16719. indices.push(3);
  16720. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16721. }
  16722. ProceduralTexture.prototype.reset = function () {
  16723. if (this._effect === undefined) {
  16724. return;
  16725. }
  16726. var engine = this.getScene().getEngine();
  16727. engine._releaseEffect(this._effect);
  16728. };
  16729. ProceduralTexture.prototype.isReady = function () {
  16730. var _this = this;
  16731. var engine = this.getScene().getEngine();
  16732. var shaders;
  16733. if (!this._fragment) {
  16734. return false;
  16735. }
  16736. if (this._fallbackTextureUsed) {
  16737. return true;
  16738. }
  16739. if (this._fragment.fragmentElement !== undefined) {
  16740. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16741. }
  16742. else {
  16743. shaders = { vertex: "procedural", fragment: this._fragment };
  16744. }
  16745. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16746. _this.releaseInternalTexture();
  16747. if (_this._fallbackTexture) {
  16748. _this._texture = _this._fallbackTexture._texture;
  16749. _this._texture.references++;
  16750. }
  16751. _this._fallbackTextureUsed = true;
  16752. });
  16753. return this._effect.isReady();
  16754. };
  16755. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16756. this._currentRefreshId = -1;
  16757. };
  16758. ProceduralTexture.prototype.setFragment = function (fragment) {
  16759. this._fragment = fragment;
  16760. };
  16761. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16762. get: function () {
  16763. return this._refreshRate;
  16764. },
  16765. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16766. set: function (value) {
  16767. this._refreshRate = value;
  16768. this.resetRefreshCounter();
  16769. },
  16770. enumerable: true,
  16771. configurable: true
  16772. });
  16773. ProceduralTexture.prototype._shouldRender = function () {
  16774. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16775. return false;
  16776. }
  16777. if (this._fallbackTextureUsed) {
  16778. return false;
  16779. }
  16780. if (this._currentRefreshId === -1) {
  16781. this._currentRefreshId = 1;
  16782. return true;
  16783. }
  16784. if (this.refreshRate === this._currentRefreshId) {
  16785. this._currentRefreshId = 1;
  16786. return true;
  16787. }
  16788. this._currentRefreshId++;
  16789. return false;
  16790. };
  16791. ProceduralTexture.prototype.getRenderSize = function () {
  16792. return this._size;
  16793. };
  16794. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16795. if (this._fallbackTextureUsed) {
  16796. return;
  16797. }
  16798. this.releaseInternalTexture();
  16799. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16800. };
  16801. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16802. if (this._uniforms.indexOf(uniformName) === -1) {
  16803. this._uniforms.push(uniformName);
  16804. }
  16805. };
  16806. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16807. if (this._samplers.indexOf(name) === -1) {
  16808. this._samplers.push(name);
  16809. }
  16810. this._textures[name] = texture;
  16811. return this;
  16812. };
  16813. ProceduralTexture.prototype.setFloat = function (name, value) {
  16814. this._checkUniform(name);
  16815. this._floats[name] = value;
  16816. return this;
  16817. };
  16818. ProceduralTexture.prototype.setFloats = function (name, value) {
  16819. this._checkUniform(name);
  16820. this._floatsArrays[name] = value;
  16821. return this;
  16822. };
  16823. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16824. this._checkUniform(name);
  16825. this._colors3[name] = value;
  16826. return this;
  16827. };
  16828. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16829. this._checkUniform(name);
  16830. this._colors4[name] = value;
  16831. return this;
  16832. };
  16833. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16834. this._checkUniform(name);
  16835. this._vectors2[name] = value;
  16836. return this;
  16837. };
  16838. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16839. this._checkUniform(name);
  16840. this._vectors3[name] = value;
  16841. return this;
  16842. };
  16843. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16844. this._checkUniform(name);
  16845. this._matrices[name] = value;
  16846. return this;
  16847. };
  16848. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16849. var scene = this.getScene();
  16850. var engine = scene.getEngine();
  16851. engine.bindFramebuffer(this._texture);
  16852. // Clear
  16853. engine.clear(scene.clearColor, true, true);
  16854. // Render
  16855. engine.enableEffect(this._effect);
  16856. engine.setState(false);
  16857. // Texture
  16858. for (var name in this._textures) {
  16859. this._effect.setTexture(name, this._textures[name]);
  16860. }
  16861. // Float
  16862. for (name in this._floats) {
  16863. this._effect.setFloat(name, this._floats[name]);
  16864. }
  16865. // Floats
  16866. for (name in this._floatsArrays) {
  16867. this._effect.setArray(name, this._floatsArrays[name]);
  16868. }
  16869. // Color3
  16870. for (name in this._colors3) {
  16871. this._effect.setColor3(name, this._colors3[name]);
  16872. }
  16873. // Color4
  16874. for (name in this._colors4) {
  16875. var color = this._colors4[name];
  16876. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16877. }
  16878. // Vector2
  16879. for (name in this._vectors2) {
  16880. this._effect.setVector2(name, this._vectors2[name]);
  16881. }
  16882. // Vector3
  16883. for (name in this._vectors3) {
  16884. this._effect.setVector3(name, this._vectors3[name]);
  16885. }
  16886. // Matrix
  16887. for (name in this._matrices) {
  16888. this._effect.setMatrix(name, this._matrices[name]);
  16889. }
  16890. // VBOs
  16891. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16892. // Draw order
  16893. engine.draw(true, 0, 6);
  16894. // Unbind
  16895. engine.unBindFramebuffer(this._texture);
  16896. };
  16897. ProceduralTexture.prototype.clone = function () {
  16898. var textureSize = this.getSize();
  16899. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16900. // Base texture
  16901. newTexture.hasAlpha = this.hasAlpha;
  16902. newTexture.level = this.level;
  16903. // RenderTarget Texture
  16904. newTexture.coordinatesMode = this.coordinatesMode;
  16905. return newTexture;
  16906. };
  16907. ProceduralTexture.prototype.dispose = function () {
  16908. var index = this.getScene()._proceduralTextures.indexOf(this);
  16909. if (index >= 0) {
  16910. this.getScene()._proceduralTextures.splice(index, 1);
  16911. }
  16912. _super.prototype.dispose.call(this);
  16913. };
  16914. return ProceduralTexture;
  16915. })(BABYLON.Texture);
  16916. BABYLON.ProceduralTexture = ProceduralTexture;
  16917. })(BABYLON || (BABYLON = {}));
  16918. var BABYLON;
  16919. (function (BABYLON) {
  16920. var MirrorTexture = (function (_super) {
  16921. __extends(MirrorTexture, _super);
  16922. function MirrorTexture(name, size, scene, generateMipMaps) {
  16923. var _this = this;
  16924. _super.call(this, name, size, scene, generateMipMaps, true);
  16925. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16926. this._transformMatrix = BABYLON.Matrix.Zero();
  16927. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16928. this.onBeforeRender = function () {
  16929. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16930. _this._savedViewMatrix = scene.getViewMatrix();
  16931. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16932. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16933. scene.clipPlane = _this.mirrorPlane;
  16934. scene.getEngine().cullBackFaces = false;
  16935. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16936. };
  16937. this.onAfterRender = function () {
  16938. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16939. scene.getEngine().cullBackFaces = true;
  16940. scene._mirroredCameraPosition = null;
  16941. delete scene.clipPlane;
  16942. };
  16943. }
  16944. MirrorTexture.prototype.clone = function () {
  16945. var textureSize = this.getSize();
  16946. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16947. // Base texture
  16948. newTexture.hasAlpha = this.hasAlpha;
  16949. newTexture.level = this.level;
  16950. // Mirror Texture
  16951. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16952. newTexture.renderList = this.renderList.slice(0);
  16953. return newTexture;
  16954. };
  16955. return MirrorTexture;
  16956. })(BABYLON.RenderTargetTexture);
  16957. BABYLON.MirrorTexture = MirrorTexture;
  16958. })(BABYLON || (BABYLON = {}));
  16959. var BABYLON;
  16960. (function (BABYLON) {
  16961. var DynamicTexture = (function (_super) {
  16962. __extends(DynamicTexture, _super);
  16963. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16965. _super.call(this, null, scene, !generateMipMaps);
  16966. this.name = name;
  16967. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16968. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16969. this._generateMipMaps = generateMipMaps;
  16970. if (options.getContext) {
  16971. this._canvas = options;
  16972. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16973. }
  16974. else {
  16975. this._canvas = document.createElement("canvas");
  16976. if (options.width) {
  16977. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16978. }
  16979. else {
  16980. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16981. }
  16982. }
  16983. var textureSize = this.getSize();
  16984. this._canvas.width = textureSize.width;
  16985. this._canvas.height = textureSize.height;
  16986. this._context = this._canvas.getContext("2d");
  16987. }
  16988. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16989. get: function () {
  16990. return true;
  16991. },
  16992. enumerable: true,
  16993. configurable: true
  16994. });
  16995. DynamicTexture.prototype.scale = function (ratio) {
  16996. var textureSize = this.getSize();
  16997. textureSize.width *= ratio;
  16998. textureSize.height *= ratio;
  16999. this._canvas.width = textureSize.width;
  17000. this._canvas.height = textureSize.height;
  17001. this.releaseInternalTexture();
  17002. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17003. };
  17004. DynamicTexture.prototype.getContext = function () {
  17005. return this._context;
  17006. };
  17007. DynamicTexture.prototype.clear = function () {
  17008. var size = this.getSize();
  17009. this._context.fillRect(0, 0, size.width, size.height);
  17010. };
  17011. DynamicTexture.prototype.update = function (invertY) {
  17012. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17013. };
  17014. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17015. if (update === void 0) { update = true; }
  17016. var size = this.getSize();
  17017. if (clearColor) {
  17018. this._context.fillStyle = clearColor;
  17019. this._context.fillRect(0, 0, size.width, size.height);
  17020. }
  17021. this._context.font = font;
  17022. if (x === null) {
  17023. var textSize = this._context.measureText(text);
  17024. x = (size.width - textSize.width) / 2;
  17025. }
  17026. this._context.fillStyle = color;
  17027. this._context.fillText(text, x, y);
  17028. if (update) {
  17029. this.update(invertY);
  17030. }
  17031. };
  17032. DynamicTexture.prototype.clone = function () {
  17033. var textureSize = this.getSize();
  17034. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17035. // Base texture
  17036. newTexture.hasAlpha = this.hasAlpha;
  17037. newTexture.level = this.level;
  17038. // Dynamic Texture
  17039. newTexture.wrapU = this.wrapU;
  17040. newTexture.wrapV = this.wrapV;
  17041. return newTexture;
  17042. };
  17043. return DynamicTexture;
  17044. })(BABYLON.Texture);
  17045. BABYLON.DynamicTexture = DynamicTexture;
  17046. })(BABYLON || (BABYLON = {}));
  17047. var BABYLON;
  17048. (function (BABYLON) {
  17049. var VideoTexture = (function (_super) {
  17050. __extends(VideoTexture, _super);
  17051. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17052. var _this = this;
  17053. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17054. if (invertY === void 0) { invertY = false; }
  17055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17056. _super.call(this, null, scene, !generateMipMaps, invertY);
  17057. this._autoLaunch = true;
  17058. this.name = name;
  17059. this.video = document.createElement("video");
  17060. this.video.autoplay = false;
  17061. this.video.loop = true;
  17062. this.video.addEventListener("canplaythrough", function () {
  17063. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17064. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17065. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17066. }
  17067. else {
  17068. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17069. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17070. generateMipMaps = false;
  17071. }
  17072. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17073. _this._texture.isReady = true;
  17074. });
  17075. urls.forEach(function (url) {
  17076. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17077. var source = document.createElement("source");
  17078. source.src = url;
  17079. _this.video.appendChild(source);
  17080. });
  17081. this._lastUpdate = BABYLON.Tools.Now;
  17082. }
  17083. VideoTexture.prototype.update = function () {
  17084. if (this._autoLaunch) {
  17085. this._autoLaunch = false;
  17086. this.video.play();
  17087. }
  17088. var now = BABYLON.Tools.Now;
  17089. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17090. return false;
  17091. }
  17092. this._lastUpdate = now;
  17093. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17094. return true;
  17095. };
  17096. return VideoTexture;
  17097. })(BABYLON.Texture);
  17098. BABYLON.VideoTexture = VideoTexture;
  17099. })(BABYLON || (BABYLON = {}));
  17100. var BABYLON;
  17101. (function (BABYLON) {
  17102. var CustomProceduralTexture = (function (_super) {
  17103. __extends(CustomProceduralTexture, _super);
  17104. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17105. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17106. this._animate = true;
  17107. this._time = 0;
  17108. this._texturePath = texturePath;
  17109. //Try to load json
  17110. this.loadJson(texturePath);
  17111. this.refreshRate = 1;
  17112. }
  17113. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17114. var _this = this;
  17115. var that = this;
  17116. function noConfigFile() {
  17117. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17118. try {
  17119. that.setFragment(that._texturePath);
  17120. }
  17121. catch (ex) {
  17122. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17123. }
  17124. }
  17125. var configFileUrl = jsonUrl + "/config.json";
  17126. var xhr = new XMLHttpRequest();
  17127. xhr.open("GET", configFileUrl, true);
  17128. xhr.addEventListener("load", function () {
  17129. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17130. try {
  17131. _this._config = JSON.parse(xhr.response);
  17132. _this.updateShaderUniforms();
  17133. _this.updateTextures();
  17134. _this.setFragment(_this._texturePath + "/custom");
  17135. _this._animate = _this._config.animate;
  17136. _this.refreshRate = _this._config.refreshrate;
  17137. }
  17138. catch (ex) {
  17139. noConfigFile();
  17140. }
  17141. }
  17142. else {
  17143. noConfigFile();
  17144. }
  17145. }, false);
  17146. xhr.addEventListener("error", function () {
  17147. noConfigFile();
  17148. }, false);
  17149. try {
  17150. xhr.send();
  17151. }
  17152. catch (ex) {
  17153. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17154. }
  17155. };
  17156. CustomProceduralTexture.prototype.isReady = function () {
  17157. if (!_super.prototype.isReady.call(this)) {
  17158. return false;
  17159. }
  17160. for (var name in this._textures) {
  17161. var texture = this._textures[name];
  17162. if (!texture.isReady()) {
  17163. return false;
  17164. }
  17165. }
  17166. return true;
  17167. };
  17168. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17169. if (this._animate) {
  17170. this._time += this.getScene().getAnimationRatio() * 0.03;
  17171. this.updateShaderUniforms();
  17172. }
  17173. _super.prototype.render.call(this, useCameraPostProcess);
  17174. };
  17175. CustomProceduralTexture.prototype.updateTextures = function () {
  17176. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17177. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17178. }
  17179. };
  17180. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17181. if (this._config) {
  17182. for (var j = 0; j < this._config.uniforms.length; j++) {
  17183. var uniform = this._config.uniforms[j];
  17184. switch (uniform.type) {
  17185. case "float":
  17186. this.setFloat(uniform.name, uniform.value);
  17187. break;
  17188. case "color3":
  17189. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17190. break;
  17191. case "color4":
  17192. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17193. break;
  17194. case "vector2":
  17195. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17196. break;
  17197. case "vector3":
  17198. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17199. break;
  17200. }
  17201. }
  17202. }
  17203. this.setFloat("time", this._time);
  17204. };
  17205. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17206. get: function () {
  17207. return this._animate;
  17208. },
  17209. set: function (value) {
  17210. this._animate = value;
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. return CustomProceduralTexture;
  17216. })(BABYLON.ProceduralTexture);
  17217. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17218. })(BABYLON || (BABYLON = {}));
  17219. var BABYLON;
  17220. (function (BABYLON) {
  17221. var WoodProceduralTexture = (function (_super) {
  17222. __extends(WoodProceduralTexture, _super);
  17223. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17224. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17225. this._ampScale = 100.0;
  17226. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17227. this.updateShaderUniforms();
  17228. this.refreshRate = 0;
  17229. }
  17230. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17231. this.setFloat("ampScale", this._ampScale);
  17232. this.setColor3("woodColor", this._woodColor);
  17233. };
  17234. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17235. get: function () {
  17236. return this._ampScale;
  17237. },
  17238. set: function (value) {
  17239. this._ampScale = value;
  17240. this.updateShaderUniforms();
  17241. },
  17242. enumerable: true,
  17243. configurable: true
  17244. });
  17245. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17246. get: function () {
  17247. return this._woodColor;
  17248. },
  17249. set: function (value) {
  17250. this._woodColor = value;
  17251. this.updateShaderUniforms();
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. return WoodProceduralTexture;
  17257. })(BABYLON.ProceduralTexture);
  17258. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17259. var FireProceduralTexture = (function (_super) {
  17260. __extends(FireProceduralTexture, _super);
  17261. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17262. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17263. this._time = 0.0;
  17264. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17265. this._autoGenerateTime = true;
  17266. this._alphaThreshold = 0.5;
  17267. this._fireColors = FireProceduralTexture.RedFireColors;
  17268. this.updateShaderUniforms();
  17269. this.refreshRate = 1;
  17270. }
  17271. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17272. this.setFloat("time", this._time);
  17273. this.setVector2("speed", this._speed);
  17274. this.setColor3("c1", this._fireColors[0]);
  17275. this.setColor3("c2", this._fireColors[1]);
  17276. this.setColor3("c3", this._fireColors[2]);
  17277. this.setColor3("c4", this._fireColors[3]);
  17278. this.setColor3("c5", this._fireColors[4]);
  17279. this.setColor3("c6", this._fireColors[5]);
  17280. this.setFloat("alphaThreshold", this._alphaThreshold);
  17281. };
  17282. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17283. if (this._autoGenerateTime) {
  17284. this._time += this.getScene().getAnimationRatio() * 0.03;
  17285. this.updateShaderUniforms();
  17286. }
  17287. _super.prototype.render.call(this, useCameraPostProcess);
  17288. };
  17289. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17290. get: function () {
  17291. return [
  17292. new BABYLON.Color3(0.5, 0.0, 1.0),
  17293. new BABYLON.Color3(0.9, 0.0, 1.0),
  17294. new BABYLON.Color3(0.2, 0.0, 1.0),
  17295. new BABYLON.Color3(1.0, 0.9, 1.0),
  17296. new BABYLON.Color3(0.1, 0.1, 1.0),
  17297. new BABYLON.Color3(0.9, 0.9, 1.0)
  17298. ];
  17299. },
  17300. enumerable: true,
  17301. configurable: true
  17302. });
  17303. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17304. get: function () {
  17305. return [
  17306. new BABYLON.Color3(0.5, 1.0, 0.0),
  17307. new BABYLON.Color3(0.5, 1.0, 0.0),
  17308. new BABYLON.Color3(0.3, 0.4, 0.0),
  17309. new BABYLON.Color3(0.5, 1.0, 0.0),
  17310. new BABYLON.Color3(0.2, 0.0, 0.0),
  17311. new BABYLON.Color3(0.5, 1.0, 0.0)
  17312. ];
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17318. get: function () {
  17319. return [
  17320. new BABYLON.Color3(0.5, 0.0, 0.1),
  17321. new BABYLON.Color3(0.9, 0.0, 0.0),
  17322. new BABYLON.Color3(0.2, 0.0, 0.0),
  17323. new BABYLON.Color3(1.0, 0.9, 0.0),
  17324. new BABYLON.Color3(0.1, 0.1, 0.1),
  17325. new BABYLON.Color3(0.9, 0.9, 0.9)
  17326. ];
  17327. },
  17328. enumerable: true,
  17329. configurable: true
  17330. });
  17331. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17332. get: function () {
  17333. return [
  17334. new BABYLON.Color3(0.1, 0.0, 0.5),
  17335. new BABYLON.Color3(0.0, 0.0, 0.5),
  17336. new BABYLON.Color3(0.1, 0.0, 0.2),
  17337. new BABYLON.Color3(0.0, 0.0, 1.0),
  17338. new BABYLON.Color3(0.1, 0.2, 0.3),
  17339. new BABYLON.Color3(0.0, 0.2, 0.9)
  17340. ];
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17346. get: function () {
  17347. return this._fireColors;
  17348. },
  17349. set: function (value) {
  17350. this._fireColors = value;
  17351. this.updateShaderUniforms();
  17352. },
  17353. enumerable: true,
  17354. configurable: true
  17355. });
  17356. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17357. get: function () {
  17358. return this._time;
  17359. },
  17360. set: function (value) {
  17361. this._time = value;
  17362. this.updateShaderUniforms();
  17363. },
  17364. enumerable: true,
  17365. configurable: true
  17366. });
  17367. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17368. get: function () {
  17369. return this._speed;
  17370. },
  17371. set: function (value) {
  17372. this._speed = value;
  17373. this.updateShaderUniforms();
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17379. get: function () {
  17380. return this._alphaThreshold;
  17381. },
  17382. set: function (value) {
  17383. this._alphaThreshold = value;
  17384. this.updateShaderUniforms();
  17385. },
  17386. enumerable: true,
  17387. configurable: true
  17388. });
  17389. return FireProceduralTexture;
  17390. })(BABYLON.ProceduralTexture);
  17391. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17392. var CloudProceduralTexture = (function (_super) {
  17393. __extends(CloudProceduralTexture, _super);
  17394. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17395. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17396. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17397. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17398. this.updateShaderUniforms();
  17399. this.refreshRate = 0;
  17400. }
  17401. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17402. this.setColor4("skyColor", this._skyColor);
  17403. this.setColor4("cloudColor", this._cloudColor);
  17404. };
  17405. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17406. get: function () {
  17407. return this._skyColor;
  17408. },
  17409. set: function (value) {
  17410. this._skyColor = value;
  17411. this.updateShaderUniforms();
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17417. get: function () {
  17418. return this._cloudColor;
  17419. },
  17420. set: function (value) {
  17421. this._cloudColor = value;
  17422. this.updateShaderUniforms();
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. return CloudProceduralTexture;
  17428. })(BABYLON.ProceduralTexture);
  17429. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17430. var GrassProceduralTexture = (function (_super) {
  17431. __extends(GrassProceduralTexture, _super);
  17432. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17433. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17434. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17435. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17436. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17437. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17438. this._grassColors = [
  17439. new BABYLON.Color3(0.29, 0.38, 0.02),
  17440. new BABYLON.Color3(0.36, 0.49, 0.09),
  17441. new BABYLON.Color3(0.51, 0.6, 0.28)
  17442. ];
  17443. this.updateShaderUniforms();
  17444. this.refreshRate = 0;
  17445. }
  17446. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17447. this.setColor3("herb1Color", this._grassColors[0]);
  17448. this.setColor3("herb2Color", this._grassColors[1]);
  17449. this.setColor3("herb3Color", this._grassColors[2]);
  17450. this.setColor3("groundColor", this._groundColor);
  17451. };
  17452. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17453. get: function () {
  17454. return this._grassColors;
  17455. },
  17456. set: function (value) {
  17457. this._grassColors = value;
  17458. this.updateShaderUniforms();
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17464. get: function () {
  17465. return this._groundColor;
  17466. },
  17467. set: function (value) {
  17468. this.groundColor = value;
  17469. this.updateShaderUniforms();
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. return GrassProceduralTexture;
  17475. })(BABYLON.ProceduralTexture);
  17476. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17477. var RoadProceduralTexture = (function (_super) {
  17478. __extends(RoadProceduralTexture, _super);
  17479. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17480. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17481. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17482. this.updateShaderUniforms();
  17483. this.refreshRate = 0;
  17484. }
  17485. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17486. this.setColor3("roadColor", this._roadColor);
  17487. };
  17488. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17489. get: function () {
  17490. return this._roadColor;
  17491. },
  17492. set: function (value) {
  17493. this._roadColor = value;
  17494. this.updateShaderUniforms();
  17495. },
  17496. enumerable: true,
  17497. configurable: true
  17498. });
  17499. return RoadProceduralTexture;
  17500. })(BABYLON.ProceduralTexture);
  17501. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17502. var BrickProceduralTexture = (function (_super) {
  17503. __extends(BrickProceduralTexture, _super);
  17504. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17505. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17506. this._numberOfBricksHeight = 15;
  17507. this._numberOfBricksWidth = 5;
  17508. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17509. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17510. this.updateShaderUniforms();
  17511. this.refreshRate = 0;
  17512. }
  17513. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17514. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17515. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17516. this.setColor3("brickColor", this._brickColor);
  17517. this.setColor3("jointColor", this._jointColor);
  17518. };
  17519. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17520. get: function () {
  17521. return this._numberOfBricksHeight;
  17522. },
  17523. set: function (value) {
  17524. this._numberOfBricksHeight = value;
  17525. this.updateShaderUniforms();
  17526. },
  17527. enumerable: true,
  17528. configurable: true
  17529. });
  17530. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17531. get: function () {
  17532. return this._numberOfBricksWidth;
  17533. },
  17534. set: function (value) {
  17535. this._numberOfBricksWidth = value;
  17536. this.updateShaderUniforms();
  17537. },
  17538. enumerable: true,
  17539. configurable: true
  17540. });
  17541. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17542. get: function () {
  17543. return this._jointColor;
  17544. },
  17545. set: function (value) {
  17546. this._jointColor = value;
  17547. this.updateShaderUniforms();
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17553. get: function () {
  17554. return this._brickColor;
  17555. },
  17556. set: function (value) {
  17557. this._brickColor = value;
  17558. this.updateShaderUniforms();
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. return BrickProceduralTexture;
  17564. })(BABYLON.ProceduralTexture);
  17565. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17566. var MarbleProceduralTexture = (function (_super) {
  17567. __extends(MarbleProceduralTexture, _super);
  17568. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17569. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17570. this._numberOfTilesHeight = 3;
  17571. this._numberOfTilesWidth = 3;
  17572. this._amplitude = 9.0;
  17573. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17574. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17575. this.updateShaderUniforms();
  17576. this.refreshRate = 0;
  17577. }
  17578. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17579. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17580. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17581. this.setFloat("amplitude", this._amplitude);
  17582. this.setColor3("marbleColor", this._marbleColor);
  17583. this.setColor3("jointColor", this._jointColor);
  17584. };
  17585. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17586. get: function () {
  17587. return this._numberOfTilesHeight;
  17588. },
  17589. set: function (value) {
  17590. this._numberOfTilesHeight = value;
  17591. this.updateShaderUniforms();
  17592. },
  17593. enumerable: true,
  17594. configurable: true
  17595. });
  17596. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17597. get: function () {
  17598. return this._numberOfTilesWidth;
  17599. },
  17600. set: function (value) {
  17601. this._numberOfTilesWidth = value;
  17602. this.updateShaderUniforms();
  17603. },
  17604. enumerable: true,
  17605. configurable: true
  17606. });
  17607. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17608. get: function () {
  17609. return this._jointColor;
  17610. },
  17611. set: function (value) {
  17612. this._jointColor = value;
  17613. this.updateShaderUniforms();
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17619. get: function () {
  17620. return this._marbleColor;
  17621. },
  17622. set: function (value) {
  17623. this._marbleColor = value;
  17624. this.updateShaderUniforms();
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. return MarbleProceduralTexture;
  17630. })(BABYLON.ProceduralTexture);
  17631. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17632. })(BABYLON || (BABYLON = {}));
  17633. var BABYLON;
  17634. (function (BABYLON) {
  17635. var EffectFallbacks = (function () {
  17636. function EffectFallbacks() {
  17637. this._defines = {};
  17638. this._currentRank = 32;
  17639. this._maxRank = -1;
  17640. }
  17641. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17642. if (!this._defines[rank]) {
  17643. if (rank < this._currentRank) {
  17644. this._currentRank = rank;
  17645. }
  17646. if (rank > this._maxRank) {
  17647. this._maxRank = rank;
  17648. }
  17649. this._defines[rank] = new Array();
  17650. }
  17651. this._defines[rank].push(define);
  17652. };
  17653. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17654. get: function () {
  17655. return this._currentRank <= this._maxRank;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17661. var currentFallbacks = this._defines[this._currentRank];
  17662. for (var index = 0; index < currentFallbacks.length; index++) {
  17663. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17664. }
  17665. this._currentRank++;
  17666. return currentDefines;
  17667. };
  17668. return EffectFallbacks;
  17669. })();
  17670. BABYLON.EffectFallbacks = EffectFallbacks;
  17671. var Effect = (function () {
  17672. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17673. var _this = this;
  17674. this._isReady = false;
  17675. this._compilationError = "";
  17676. this._valueCache = [];
  17677. this._engine = engine;
  17678. this.name = baseName;
  17679. this.defines = defines;
  17680. this._uniformsNames = uniformsNames.concat(samplers);
  17681. this._samplers = samplers;
  17682. this._attributesNames = attributesNames;
  17683. this.onError = onError;
  17684. this.onCompiled = onCompiled;
  17685. var vertexSource;
  17686. var fragmentSource;
  17687. if (baseName.vertexElement) {
  17688. vertexSource = document.getElementById(baseName.vertexElement);
  17689. if (!vertexSource) {
  17690. vertexSource = baseName.vertexElement;
  17691. }
  17692. }
  17693. else {
  17694. vertexSource = baseName.vertex || baseName;
  17695. }
  17696. if (baseName.fragmentElement) {
  17697. fragmentSource = document.getElementById(baseName.fragmentElement);
  17698. if (!fragmentSource) {
  17699. fragmentSource = baseName.fragmentElement;
  17700. }
  17701. }
  17702. else {
  17703. fragmentSource = baseName.fragment || baseName;
  17704. }
  17705. this._loadVertexShader(vertexSource, function (vertexCode) {
  17706. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17707. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17708. });
  17709. });
  17710. }
  17711. // Properties
  17712. Effect.prototype.isReady = function () {
  17713. return this._isReady;
  17714. };
  17715. Effect.prototype.getProgram = function () {
  17716. return this._program;
  17717. };
  17718. Effect.prototype.getAttributesNames = function () {
  17719. return this._attributesNames;
  17720. };
  17721. Effect.prototype.getAttributeLocation = function (index) {
  17722. return this._attributes[index];
  17723. };
  17724. Effect.prototype.getAttributeLocationByName = function (name) {
  17725. var index = this._attributesNames.indexOf(name);
  17726. return this._attributes[index];
  17727. };
  17728. Effect.prototype.getAttributesCount = function () {
  17729. return this._attributes.length;
  17730. };
  17731. Effect.prototype.getUniformIndex = function (uniformName) {
  17732. return this._uniformsNames.indexOf(uniformName);
  17733. };
  17734. Effect.prototype.getUniform = function (uniformName) {
  17735. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17736. };
  17737. Effect.prototype.getSamplers = function () {
  17738. return this._samplers;
  17739. };
  17740. Effect.prototype.getCompilationError = function () {
  17741. return this._compilationError;
  17742. };
  17743. // Methods
  17744. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17745. // DOM element ?
  17746. if (vertex instanceof HTMLElement) {
  17747. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17748. callback(vertexCode);
  17749. return;
  17750. }
  17751. // Is in local store ?
  17752. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17753. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17754. return;
  17755. }
  17756. var vertexShaderUrl;
  17757. if (vertex[0] === "." || vertex[0] === "/") {
  17758. vertexShaderUrl = vertex;
  17759. }
  17760. else {
  17761. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17762. }
  17763. // Vertex shader
  17764. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17765. };
  17766. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17767. // DOM element ?
  17768. if (fragment instanceof HTMLElement) {
  17769. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17770. callback(fragmentCode);
  17771. return;
  17772. }
  17773. // Is in local store ?
  17774. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17775. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17776. return;
  17777. }
  17778. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17779. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17780. return;
  17781. }
  17782. var fragmentShaderUrl;
  17783. if (fragment[0] === "." || fragment[0] === "/") {
  17784. fragmentShaderUrl = fragment;
  17785. }
  17786. else {
  17787. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17788. }
  17789. // Fragment shader
  17790. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17791. };
  17792. Effect.prototype._dumpShadersName = function () {
  17793. if (this.name.vertexElement) {
  17794. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17795. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17796. }
  17797. else if (this.name.vertex) {
  17798. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17799. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17800. }
  17801. else {
  17802. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17803. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17804. }
  17805. };
  17806. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17807. try {
  17808. var engine = this._engine;
  17809. if (!engine.getCaps().highPrecisionShaderSupported) {
  17810. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17811. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17812. }
  17813. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17814. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17815. this._attributes = engine.getAttributes(this._program, attributesNames);
  17816. for (var index = 0; index < this._samplers.length; index++) {
  17817. var sampler = this.getUniform(this._samplers[index]);
  17818. if (sampler == null) {
  17819. this._samplers.splice(index, 1);
  17820. index--;
  17821. }
  17822. }
  17823. engine.bindSamplers(this);
  17824. this._isReady = true;
  17825. if (this.onCompiled) {
  17826. this.onCompiled(this);
  17827. }
  17828. }
  17829. catch (e) {
  17830. // Is it a problem with precision?
  17831. if (e.message.indexOf("highp") !== -1) {
  17832. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17833. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17834. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17835. return;
  17836. }
  17837. // Let's go through fallbacks then
  17838. if (fallbacks && fallbacks.isMoreFallbacks) {
  17839. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17840. this._dumpShadersName();
  17841. defines = fallbacks.reduce(defines);
  17842. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17843. }
  17844. else {
  17845. BABYLON.Tools.Error("Unable to compile effect: ");
  17846. this._dumpShadersName();
  17847. BABYLON.Tools.Error("Defines: " + defines);
  17848. BABYLON.Tools.Error("Error: " + e.message);
  17849. this._compilationError = e.message;
  17850. if (this.onError) {
  17851. this.onError(this, this._compilationError);
  17852. }
  17853. }
  17854. }
  17855. };
  17856. Object.defineProperty(Effect.prototype, "isSupported", {
  17857. get: function () {
  17858. return this._compilationError === "";
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Effect.prototype._bindTexture = function (channel, texture) {
  17864. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17865. };
  17866. Effect.prototype.setTexture = function (channel, texture) {
  17867. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17868. };
  17869. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17870. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17871. };
  17872. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17873. if (!this._valueCache[uniformName]) {
  17874. this._valueCache[uniformName] = new BABYLON.Matrix();
  17875. }
  17876. for (var index = 0; index < 16; index++) {
  17877. this._valueCache[uniformName].m[index] = matrix.m[index];
  17878. }
  17879. };
  17880. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17881. if (!this._valueCache[uniformName]) {
  17882. this._valueCache[uniformName] = [x, y];
  17883. return;
  17884. }
  17885. this._valueCache[uniformName][0] = x;
  17886. this._valueCache[uniformName][1] = y;
  17887. };
  17888. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17889. if (!this._valueCache[uniformName]) {
  17890. this._valueCache[uniformName] = [x, y, z];
  17891. return;
  17892. }
  17893. this._valueCache[uniformName][0] = x;
  17894. this._valueCache[uniformName][1] = y;
  17895. this._valueCache[uniformName][2] = z;
  17896. };
  17897. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17898. if (!this._valueCache[uniformName]) {
  17899. this._valueCache[uniformName] = [x, y, z, w];
  17900. return;
  17901. }
  17902. this._valueCache[uniformName][0] = x;
  17903. this._valueCache[uniformName][1] = y;
  17904. this._valueCache[uniformName][2] = z;
  17905. this._valueCache[uniformName][3] = w;
  17906. };
  17907. Effect.prototype.setArray = function (uniformName, array) {
  17908. this._engine.setArray(this.getUniform(uniformName), array);
  17909. return this;
  17910. };
  17911. Effect.prototype.setArray2 = function (uniformName, array) {
  17912. this._engine.setArray2(this.getUniform(uniformName), array);
  17913. return this;
  17914. };
  17915. Effect.prototype.setArray3 = function (uniformName, array) {
  17916. this._engine.setArray3(this.getUniform(uniformName), array);
  17917. return this;
  17918. };
  17919. Effect.prototype.setArray4 = function (uniformName, array) {
  17920. this._engine.setArray4(this.getUniform(uniformName), array);
  17921. return this;
  17922. };
  17923. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17924. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17925. return this;
  17926. };
  17927. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17928. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17929. return this;
  17930. this._cacheMatrix(uniformName, matrix);
  17931. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17932. return this;
  17933. };
  17934. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17935. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17936. return this;
  17937. };
  17938. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  17939. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  17940. return this;
  17941. };
  17942. Effect.prototype.setFloat = function (uniformName, value) {
  17943. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17944. return this;
  17945. this._valueCache[uniformName] = value;
  17946. this._engine.setFloat(this.getUniform(uniformName), value);
  17947. return this;
  17948. };
  17949. Effect.prototype.setBool = function (uniformName, bool) {
  17950. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17951. return this;
  17952. this._valueCache[uniformName] = bool;
  17953. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17954. return this;
  17955. };
  17956. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17957. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17958. return this;
  17959. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17960. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17961. return this;
  17962. };
  17963. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17964. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17965. return this;
  17966. this._cacheFloat2(uniformName, x, y);
  17967. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17968. return this;
  17969. };
  17970. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17971. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17972. return this;
  17973. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17974. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17975. return this;
  17976. };
  17977. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17978. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17979. return this;
  17980. this._cacheFloat3(uniformName, x, y, z);
  17981. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17982. return this;
  17983. };
  17984. Effect.prototype.setVector4 = function (uniformName, vector4) {
  17985. 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)
  17986. return this;
  17987. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  17988. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  17989. return this;
  17990. };
  17991. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17992. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17993. return this;
  17994. this._cacheFloat4(uniformName, x, y, z, w);
  17995. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17996. return this;
  17997. };
  17998. Effect.prototype.setColor3 = function (uniformName, color3) {
  17999. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18000. return this;
  18001. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18002. this._engine.setColor3(this.getUniform(uniformName), color3);
  18003. return this;
  18004. };
  18005. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18006. 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)
  18007. return this;
  18008. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18009. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18010. return this;
  18011. };
  18012. // Statics
  18013. Effect.ShadersStore = {};
  18014. return Effect;
  18015. })();
  18016. BABYLON.Effect = Effect;
  18017. })(BABYLON || (BABYLON = {}));
  18018. var BABYLON;
  18019. (function (BABYLON) {
  18020. var MaterialDefines = (function () {
  18021. function MaterialDefines() {
  18022. }
  18023. MaterialDefines.prototype.isEqual = function (other) {
  18024. for (var index = 0; index < this._keys.length; index++) {
  18025. var prop = this._keys[index];
  18026. if (this[prop] !== other[prop]) {
  18027. return false;
  18028. }
  18029. }
  18030. return true;
  18031. };
  18032. MaterialDefines.prototype.cloneTo = function (other) {
  18033. for (var index = 0; index < this._keys.length; index++) {
  18034. var prop = this._keys[index];
  18035. other[prop] = this[prop];
  18036. }
  18037. };
  18038. MaterialDefines.prototype.reset = function () {
  18039. for (var index = 0; index < this._keys.length; index++) {
  18040. var prop = this._keys[index];
  18041. if (prop === "BonesPerMesh") {
  18042. this[prop] = 0;
  18043. continue;
  18044. }
  18045. this[prop] = false;
  18046. }
  18047. };
  18048. MaterialDefines.prototype.toString = function () {
  18049. var result = "";
  18050. for (var index = 0; index < this._keys.length; index++) {
  18051. var prop = this._keys[index];
  18052. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18053. result += "#define BonesPerMesh " + this[prop] + "\n";
  18054. continue;
  18055. }
  18056. if (this[prop]) {
  18057. result += "#define " + prop + "\n";
  18058. }
  18059. }
  18060. return result;
  18061. };
  18062. return MaterialDefines;
  18063. })();
  18064. BABYLON.MaterialDefines = MaterialDefines;
  18065. var Material = (function () {
  18066. function Material(name, scene, doNotAdd) {
  18067. this.name = name;
  18068. this.checkReadyOnEveryCall = false;
  18069. this.checkReadyOnlyOnce = false;
  18070. this.state = "";
  18071. this.alpha = 1.0;
  18072. this.backFaceCulling = true;
  18073. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18074. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18075. this.disableDepthWrite = false;
  18076. this.fogEnabled = true;
  18077. this._wasPreviouslyReady = false;
  18078. this._fillMode = Material.TriangleFillMode;
  18079. this.pointSize = 1.0;
  18080. this.zOffset = 0;
  18081. this.id = name;
  18082. this._scene = scene;
  18083. if (!doNotAdd) {
  18084. scene.materials.push(this);
  18085. }
  18086. }
  18087. Object.defineProperty(Material, "TriangleFillMode", {
  18088. get: function () {
  18089. return Material._TriangleFillMode;
  18090. },
  18091. enumerable: true,
  18092. configurable: true
  18093. });
  18094. Object.defineProperty(Material, "WireFrameFillMode", {
  18095. get: function () {
  18096. return Material._WireFrameFillMode;
  18097. },
  18098. enumerable: true,
  18099. configurable: true
  18100. });
  18101. Object.defineProperty(Material, "PointFillMode", {
  18102. get: function () {
  18103. return Material._PointFillMode;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18109. get: function () {
  18110. return Material._ClockWiseSideOrientation;
  18111. },
  18112. enumerable: true,
  18113. configurable: true
  18114. });
  18115. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18116. get: function () {
  18117. return Material._CounterClockWiseSideOrientation;
  18118. },
  18119. enumerable: true,
  18120. configurable: true
  18121. });
  18122. Object.defineProperty(Material.prototype, "wireframe", {
  18123. get: function () {
  18124. return this._fillMode === Material.WireFrameFillMode;
  18125. },
  18126. set: function (value) {
  18127. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18128. },
  18129. enumerable: true,
  18130. configurable: true
  18131. });
  18132. Object.defineProperty(Material.prototype, "pointsCloud", {
  18133. get: function () {
  18134. return this._fillMode === Material.PointFillMode;
  18135. },
  18136. set: function (value) {
  18137. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18138. },
  18139. enumerable: true,
  18140. configurable: true
  18141. });
  18142. Object.defineProperty(Material.prototype, "fillMode", {
  18143. get: function () {
  18144. return this._fillMode;
  18145. },
  18146. set: function (value) {
  18147. this._fillMode = value;
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. Material.prototype.isReady = function (mesh, useInstances) {
  18153. return true;
  18154. };
  18155. Material.prototype.getEffect = function () {
  18156. return this._effect;
  18157. };
  18158. Material.prototype.getScene = function () {
  18159. return this._scene;
  18160. };
  18161. Material.prototype.needAlphaBlending = function () {
  18162. return (this.alpha < 1.0);
  18163. };
  18164. Material.prototype.needAlphaTesting = function () {
  18165. return false;
  18166. };
  18167. Material.prototype.getAlphaTestTexture = function () {
  18168. return null;
  18169. };
  18170. Material.prototype.trackCreation = function (onCompiled, onError) {
  18171. };
  18172. Material.prototype._preBind = function () {
  18173. var engine = this._scene.getEngine();
  18174. engine.enableEffect(this._effect);
  18175. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18176. };
  18177. Material.prototype.bind = function (world, mesh) {
  18178. this._scene._cachedMaterial = this;
  18179. if (this.onBind) {
  18180. this.onBind(this, mesh);
  18181. }
  18182. if (this.disableDepthWrite) {
  18183. var engine = this._scene.getEngine();
  18184. this._cachedDepthWriteState = engine.getDepthWrite();
  18185. engine.setDepthWrite(false);
  18186. }
  18187. };
  18188. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18189. };
  18190. Material.prototype.unbind = function () {
  18191. if (this.disableDepthWrite) {
  18192. var engine = this._scene.getEngine();
  18193. engine.setDepthWrite(this._cachedDepthWriteState);
  18194. }
  18195. };
  18196. Material.prototype.clone = function (name) {
  18197. return null;
  18198. };
  18199. Material.prototype.getBindedMeshes = function () {
  18200. var result = new Array();
  18201. for (var index = 0; index < this._scene.meshes.length; index++) {
  18202. var mesh = this._scene.meshes[index];
  18203. if (mesh.material === this) {
  18204. result.push(mesh);
  18205. }
  18206. }
  18207. return result;
  18208. };
  18209. Material.prototype.dispose = function (forceDisposeEffect) {
  18210. // Animations
  18211. this.getScene().stopAnimation(this);
  18212. // Remove from scene
  18213. var index = this._scene.materials.indexOf(this);
  18214. if (index >= 0) {
  18215. this._scene.materials.splice(index, 1);
  18216. }
  18217. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18218. if (forceDisposeEffect && this._effect) {
  18219. this._scene.getEngine()._releaseEffect(this._effect);
  18220. this._effect = null;
  18221. }
  18222. // Remove from meshes
  18223. for (index = 0; index < this._scene.meshes.length; index++) {
  18224. var mesh = this._scene.meshes[index];
  18225. if (mesh.material === this) {
  18226. mesh.material = null;
  18227. }
  18228. }
  18229. // Callback
  18230. if (this.onDispose) {
  18231. this.onDispose();
  18232. }
  18233. };
  18234. Material.prototype.copyTo = function (other) {
  18235. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18236. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18237. other.alpha = this.alpha;
  18238. other.fillMode = this.fillMode;
  18239. other.backFaceCulling = this.backFaceCulling;
  18240. other.wireframe = this.wireframe;
  18241. other.fogEnabled = this.fogEnabled;
  18242. other.wireframe = this.wireframe;
  18243. other.zOffset = this.zOffset;
  18244. other.alphaMode = this.alphaMode;
  18245. other.sideOrientation = this.sideOrientation;
  18246. other.disableDepthWrite = this.disableDepthWrite;
  18247. other.pointSize = this.pointSize;
  18248. other.pointsCloud = this.pointsCloud;
  18249. };
  18250. Material._TriangleFillMode = 0;
  18251. Material._WireFrameFillMode = 1;
  18252. Material._PointFillMode = 2;
  18253. Material._ClockWiseSideOrientation = 0;
  18254. Material._CounterClockWiseSideOrientation = 1;
  18255. return Material;
  18256. })();
  18257. BABYLON.Material = Material;
  18258. })(BABYLON || (BABYLON = {}));
  18259. var BABYLON;
  18260. (function (BABYLON) {
  18261. var maxSimultaneousLights = 4;
  18262. var FresnelParameters = (function () {
  18263. function FresnelParameters() {
  18264. this.isEnabled = true;
  18265. this.leftColor = BABYLON.Color3.White();
  18266. this.rightColor = BABYLON.Color3.Black();
  18267. this.bias = 0;
  18268. this.power = 1;
  18269. }
  18270. FresnelParameters.prototype.clone = function () {
  18271. var newFresnelParameters = new FresnelParameters();
  18272. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18273. return new FresnelParameters;
  18274. };
  18275. return FresnelParameters;
  18276. })();
  18277. BABYLON.FresnelParameters = FresnelParameters;
  18278. var StandardMaterialDefines = (function (_super) {
  18279. __extends(StandardMaterialDefines, _super);
  18280. function StandardMaterialDefines() {
  18281. _super.call(this);
  18282. this.DIFFUSE = false;
  18283. this.AMBIENT = false;
  18284. this.OPACITY = false;
  18285. this.OPACITYRGB = false;
  18286. this.REFLECTION = false;
  18287. this.EMISSIVE = false;
  18288. this.SPECULAR = false;
  18289. this.BUMP = false;
  18290. this.SPECULAROVERALPHA = false;
  18291. this.CLIPPLANE = false;
  18292. this.ALPHATEST = false;
  18293. this.ALPHAFROMDIFFUSE = false;
  18294. this.POINTSIZE = false;
  18295. this.FOG = false;
  18296. this.LIGHT0 = false;
  18297. this.LIGHT1 = false;
  18298. this.LIGHT2 = false;
  18299. this.LIGHT3 = false;
  18300. this.SPOTLIGHT0 = false;
  18301. this.SPOTLIGHT1 = false;
  18302. this.SPOTLIGHT2 = false;
  18303. this.SPOTLIGHT3 = false;
  18304. this.HEMILIGHT0 = false;
  18305. this.HEMILIGHT1 = false;
  18306. this.HEMILIGHT2 = false;
  18307. this.HEMILIGHT3 = false;
  18308. this.POINTLIGHT0 = false;
  18309. this.POINTLIGHT1 = false;
  18310. this.POINTLIGHT2 = false;
  18311. this.POINTLIGHT3 = false;
  18312. this.DIRLIGHT0 = false;
  18313. this.DIRLIGHT1 = false;
  18314. this.DIRLIGHT2 = false;
  18315. this.DIRLIGHT3 = false;
  18316. this.SPECULARTERM = false;
  18317. this.SHADOW0 = false;
  18318. this.SHADOW1 = false;
  18319. this.SHADOW2 = false;
  18320. this.SHADOW3 = false;
  18321. this.SHADOWS = false;
  18322. this.SHADOWVSM0 = false;
  18323. this.SHADOWVSM1 = false;
  18324. this.SHADOWVSM2 = false;
  18325. this.SHADOWVSM3 = false;
  18326. this.SHADOWPCF0 = false;
  18327. this.SHADOWPCF1 = false;
  18328. this.SHADOWPCF2 = false;
  18329. this.SHADOWPCF3 = false;
  18330. this.DIFFUSEFRESNEL = false;
  18331. this.OPACITYFRESNEL = false;
  18332. this.REFLECTIONFRESNEL = false;
  18333. this.EMISSIVEFRESNEL = false;
  18334. this.FRESNEL = false;
  18335. this.NORMAL = false;
  18336. this.UV1 = false;
  18337. this.UV2 = false;
  18338. this.VERTEXCOLOR = false;
  18339. this.VERTEXALPHA = false;
  18340. this.BONES = false;
  18341. this.BONES4 = false;
  18342. this.BonesPerMesh = 0;
  18343. this.INSTANCES = false;
  18344. this.GLOSSINESS = false;
  18345. this.ROUGHNESS = false;
  18346. this.EMISSIVEASILLUMINATION = false;
  18347. this.LINKEMISSIVEWITHDIFFUSE = false;
  18348. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18349. this.LIGHTMAP = false;
  18350. this.USELIGHTMAPASSHADOWMAP = false;
  18351. this.REFLECTIONMAP_3D = false;
  18352. this.REFLECTIONMAP_SPHERICAL = false;
  18353. this.REFLECTIONMAP_PLANAR = false;
  18354. this.REFLECTIONMAP_CUBIC = false;
  18355. this.REFLECTIONMAP_PROJECTION = false;
  18356. this.REFLECTIONMAP_SKYBOX = false;
  18357. this.REFLECTIONMAP_EXPLICIT = false;
  18358. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18359. this.INVERTCUBICMAP = false;
  18360. this._keys = Object.keys(this);
  18361. }
  18362. return StandardMaterialDefines;
  18363. })(BABYLON.MaterialDefines);
  18364. var StandardMaterial = (function (_super) {
  18365. __extends(StandardMaterial, _super);
  18366. function StandardMaterial(name, scene) {
  18367. var _this = this;
  18368. _super.call(this, name, scene);
  18369. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18370. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18371. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18372. this.specularPower = 64;
  18373. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18374. this.useAlphaFromDiffuseTexture = false;
  18375. this.useEmissiveAsIllumination = false;
  18376. this.linkEmissiveWithDiffuse = false;
  18377. this.useReflectionFresnelFromSpecular = false;
  18378. this.useSpecularOverAlpha = true;
  18379. this.disableLighting = false;
  18380. this.roughness = 0;
  18381. this.useLightmapAsShadowmap = false;
  18382. this.useGlossinessFromSpecularMapAlpha = false;
  18383. this._renderTargets = new BABYLON.SmartArray(16);
  18384. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18385. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18386. this._defines = new StandardMaterialDefines();
  18387. this._cachedDefines = new StandardMaterialDefines();
  18388. this._cachedDefines.BonesPerMesh = -1;
  18389. this.getRenderTargetTextures = function () {
  18390. _this._renderTargets.reset();
  18391. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18392. _this._renderTargets.push(_this.reflectionTexture);
  18393. }
  18394. return _this._renderTargets;
  18395. };
  18396. }
  18397. StandardMaterial.prototype.needAlphaBlending = function () {
  18398. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18399. };
  18400. StandardMaterial.prototype.needAlphaTesting = function () {
  18401. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18402. };
  18403. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18404. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18405. };
  18406. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18407. return this.diffuseTexture;
  18408. };
  18409. // Methods
  18410. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18411. if (!mesh) {
  18412. return true;
  18413. }
  18414. if (this._defines.INSTANCES !== useInstances) {
  18415. return false;
  18416. }
  18417. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18418. return true;
  18419. }
  18420. return false;
  18421. };
  18422. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18423. var lightIndex = 0;
  18424. var needNormals = false;
  18425. for (var index = 0; index < scene.lights.length; index++) {
  18426. var light = scene.lights[index];
  18427. if (!light.isEnabled()) {
  18428. continue;
  18429. }
  18430. // Excluded check
  18431. if (light._excludedMeshesIds.length > 0) {
  18432. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18433. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18434. if (excludedMesh) {
  18435. light.excludedMeshes.push(excludedMesh);
  18436. }
  18437. }
  18438. light._excludedMeshesIds = [];
  18439. }
  18440. // Included check
  18441. if (light._includedOnlyMeshesIds.length > 0) {
  18442. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18443. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18444. if (includedOnlyMesh) {
  18445. light.includedOnlyMeshes.push(includedOnlyMesh);
  18446. }
  18447. }
  18448. light._includedOnlyMeshesIds = [];
  18449. }
  18450. if (!light.canAffectMesh(mesh)) {
  18451. continue;
  18452. }
  18453. needNormals = true;
  18454. defines["LIGHT" + lightIndex] = true;
  18455. var type;
  18456. if (light instanceof BABYLON.SpotLight) {
  18457. type = "SPOTLIGHT" + lightIndex;
  18458. }
  18459. else if (light instanceof BABYLON.HemisphericLight) {
  18460. type = "HEMILIGHT" + lightIndex;
  18461. }
  18462. else if (light instanceof BABYLON.PointLight) {
  18463. type = "POINTLIGHT" + lightIndex;
  18464. }
  18465. else {
  18466. type = "DIRLIGHT" + lightIndex;
  18467. }
  18468. defines[type] = true;
  18469. // Specular
  18470. if (!light.specular.equalsFloats(0, 0, 0)) {
  18471. defines["SPECULARTERM"] = true;
  18472. }
  18473. // Shadows
  18474. if (scene.shadowsEnabled) {
  18475. var shadowGenerator = light.getShadowGenerator();
  18476. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18477. defines["SHADOW" + lightIndex] = true;
  18478. defines["SHADOWS"] = true;
  18479. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18480. defines["SHADOWVSM" + lightIndex] = true;
  18481. }
  18482. if (shadowGenerator.usePoissonSampling) {
  18483. defines["SHADOWPCF" + lightIndex] = true;
  18484. }
  18485. }
  18486. }
  18487. lightIndex++;
  18488. if (lightIndex === maxSimultaneousLights)
  18489. break;
  18490. }
  18491. return needNormals;
  18492. };
  18493. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18494. var lightIndex = 0;
  18495. for (var index = 0; index < scene.lights.length; index++) {
  18496. var light = scene.lights[index];
  18497. if (!light.isEnabled()) {
  18498. continue;
  18499. }
  18500. if (!light.canAffectMesh(mesh)) {
  18501. continue;
  18502. }
  18503. if (light instanceof BABYLON.PointLight) {
  18504. // Point Light
  18505. light.transferToEffect(effect, "vLightData" + lightIndex);
  18506. }
  18507. else if (light instanceof BABYLON.DirectionalLight) {
  18508. // Directional Light
  18509. light.transferToEffect(effect, "vLightData" + lightIndex);
  18510. }
  18511. else if (light instanceof BABYLON.SpotLight) {
  18512. // Spot Light
  18513. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18514. }
  18515. else if (light instanceof BABYLON.HemisphericLight) {
  18516. // Hemispheric Light
  18517. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18518. }
  18519. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18520. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18521. if (defines["SPECULARTERM"]) {
  18522. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18523. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18524. }
  18525. // Shadows
  18526. if (scene.shadowsEnabled) {
  18527. var shadowGenerator = light.getShadowGenerator();
  18528. if (mesh.receiveShadows && shadowGenerator) {
  18529. if (!light.needCube()) {
  18530. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18531. }
  18532. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18533. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18534. }
  18535. }
  18536. lightIndex++;
  18537. if (lightIndex === maxSimultaneousLights)
  18538. break;
  18539. }
  18540. };
  18541. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18542. if (this.checkReadyOnlyOnce) {
  18543. if (this._wasPreviouslyReady) {
  18544. return true;
  18545. }
  18546. }
  18547. var scene = this.getScene();
  18548. if (!this.checkReadyOnEveryCall) {
  18549. if (this._renderId === scene.getRenderId()) {
  18550. if (this._checkCache(scene, mesh, useInstances)) {
  18551. return true;
  18552. }
  18553. }
  18554. }
  18555. var engine = scene.getEngine();
  18556. var needNormals = false;
  18557. var needUVs = false;
  18558. this._defines.reset();
  18559. // Textures
  18560. if (scene.texturesEnabled) {
  18561. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18562. if (!this.diffuseTexture.isReady()) {
  18563. return false;
  18564. }
  18565. else {
  18566. needUVs = true;
  18567. this._defines.DIFFUSE = true;
  18568. }
  18569. }
  18570. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18571. if (!this.ambientTexture.isReady()) {
  18572. return false;
  18573. }
  18574. else {
  18575. needUVs = true;
  18576. this._defines.AMBIENT = true;
  18577. }
  18578. }
  18579. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18580. if (!this.opacityTexture.isReady()) {
  18581. return false;
  18582. }
  18583. else {
  18584. needUVs = true;
  18585. this._defines.OPACITY = true;
  18586. if (this.opacityTexture.getAlphaFromRGB) {
  18587. this._defines.OPACITYRGB = true;
  18588. }
  18589. }
  18590. }
  18591. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18592. if (!this.reflectionTexture.isReady()) {
  18593. return false;
  18594. }
  18595. else {
  18596. needNormals = true;
  18597. this._defines.REFLECTION = true;
  18598. if (this.roughness > 0) {
  18599. this._defines.ROUGHNESS = true;
  18600. }
  18601. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18602. this._defines.INVERTCUBICMAP = true;
  18603. }
  18604. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18605. switch (this.reflectionTexture.coordinatesMode) {
  18606. case BABYLON.Texture.CUBIC_MODE:
  18607. case BABYLON.Texture.INVCUBIC_MODE:
  18608. this._defines.REFLECTIONMAP_CUBIC = true;
  18609. break;
  18610. case BABYLON.Texture.EXPLICIT_MODE:
  18611. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18612. break;
  18613. case BABYLON.Texture.PLANAR_MODE:
  18614. this._defines.REFLECTIONMAP_PLANAR = true;
  18615. break;
  18616. case BABYLON.Texture.PROJECTION_MODE:
  18617. this._defines.REFLECTIONMAP_PROJECTION = true;
  18618. break;
  18619. case BABYLON.Texture.SKYBOX_MODE:
  18620. this._defines.REFLECTIONMAP_SKYBOX = true;
  18621. break;
  18622. case BABYLON.Texture.SPHERICAL_MODE:
  18623. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18624. break;
  18625. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18626. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18627. break;
  18628. }
  18629. }
  18630. }
  18631. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18632. if (!this.emissiveTexture.isReady()) {
  18633. return false;
  18634. }
  18635. else {
  18636. needUVs = true;
  18637. this._defines.EMISSIVE = true;
  18638. }
  18639. }
  18640. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18641. if (!this.lightmapTexture.isReady()) {
  18642. return false;
  18643. }
  18644. else {
  18645. needUVs = true;
  18646. this._defines.LIGHTMAP = true;
  18647. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18648. }
  18649. }
  18650. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18651. if (!this.specularTexture.isReady()) {
  18652. return false;
  18653. }
  18654. else {
  18655. needUVs = true;
  18656. this._defines.SPECULAR = true;
  18657. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18658. }
  18659. }
  18660. }
  18661. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18662. if (!this.bumpTexture.isReady()) {
  18663. return false;
  18664. }
  18665. else {
  18666. needUVs = true;
  18667. this._defines.BUMP = true;
  18668. }
  18669. }
  18670. // Effect
  18671. if (scene.clipPlane) {
  18672. this._defines.CLIPPLANE = true;
  18673. }
  18674. if (engine.getAlphaTesting()) {
  18675. this._defines.ALPHATEST = true;
  18676. }
  18677. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18678. this._defines.ALPHAFROMDIFFUSE = true;
  18679. }
  18680. if (this.useEmissiveAsIllumination) {
  18681. this._defines.EMISSIVEASILLUMINATION = true;
  18682. }
  18683. if (this.linkEmissiveWithDiffuse) {
  18684. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18685. }
  18686. if (this.useReflectionFresnelFromSpecular) {
  18687. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18688. }
  18689. // Point size
  18690. if (this.pointsCloud || scene.forcePointsCloud) {
  18691. this._defines.POINTSIZE = true;
  18692. }
  18693. // Fog
  18694. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18695. this._defines.FOG = true;
  18696. }
  18697. if (scene.lightsEnabled && !this.disableLighting) {
  18698. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18699. }
  18700. if (StandardMaterial.FresnelEnabled) {
  18701. // Fresnel
  18702. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18703. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18704. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18705. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18706. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18707. this._defines.DIFFUSEFRESNEL = true;
  18708. }
  18709. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18710. this._defines.OPACITYFRESNEL = true;
  18711. }
  18712. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18713. this._defines.REFLECTIONFRESNEL = true;
  18714. }
  18715. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18716. this._defines.EMISSIVEFRESNEL = true;
  18717. }
  18718. needNormals = true;
  18719. this._defines.FRESNEL = true;
  18720. }
  18721. }
  18722. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18723. this._defines.SPECULAROVERALPHA = true;
  18724. }
  18725. // Attribs
  18726. if (mesh) {
  18727. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18728. this._defines.NORMAL = true;
  18729. }
  18730. if (needUVs) {
  18731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18732. this._defines.UV1 = true;
  18733. }
  18734. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18735. this._defines.UV2 = true;
  18736. }
  18737. }
  18738. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18739. this._defines.VERTEXCOLOR = true;
  18740. if (mesh.hasVertexAlpha) {
  18741. this._defines.VERTEXALPHA = true;
  18742. }
  18743. }
  18744. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18745. this._defines.BONES = true;
  18746. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18747. this._defines.BONES4 = true;
  18748. }
  18749. // Instances
  18750. if (useInstances) {
  18751. this._defines.INSTANCES = true;
  18752. }
  18753. }
  18754. // Get correct effect
  18755. if (!this._defines.isEqual(this._cachedDefines)) {
  18756. this._defines.cloneTo(this._cachedDefines);
  18757. scene.resetCachedMaterial();
  18758. // Fallbacks
  18759. var fallbacks = new BABYLON.EffectFallbacks();
  18760. if (this._defines.REFLECTION) {
  18761. fallbacks.addFallback(0, "REFLECTION");
  18762. }
  18763. if (this._defines.SPECULAR) {
  18764. fallbacks.addFallback(0, "SPECULAR");
  18765. }
  18766. if (this._defines.BUMP) {
  18767. fallbacks.addFallback(0, "BUMP");
  18768. }
  18769. if (this._defines.SPECULAROVERALPHA) {
  18770. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18771. }
  18772. if (this._defines.FOG) {
  18773. fallbacks.addFallback(1, "FOG");
  18774. }
  18775. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18776. if (!this._defines["LIGHT" + lightIndex]) {
  18777. continue;
  18778. }
  18779. if (lightIndex > 0) {
  18780. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18781. }
  18782. if (this._defines["SHADOW" + lightIndex]) {
  18783. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18784. }
  18785. if (this._defines["SHADOWPCF" + lightIndex]) {
  18786. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18787. }
  18788. if (this._defines["SHADOWVSM" + lightIndex]) {
  18789. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18790. }
  18791. }
  18792. if (this._defines.SPECULARTERM) {
  18793. fallbacks.addFallback(0, "SPECULARTERM");
  18794. }
  18795. if (this._defines.DIFFUSEFRESNEL) {
  18796. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18797. }
  18798. if (this._defines.OPACITYFRESNEL) {
  18799. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18800. }
  18801. if (this._defines.REFLECTIONFRESNEL) {
  18802. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18803. }
  18804. if (this._defines.EMISSIVEFRESNEL) {
  18805. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18806. }
  18807. if (this._defines.FRESNEL) {
  18808. fallbacks.addFallback(4, "FRESNEL");
  18809. }
  18810. if (this._defines.BONES4) {
  18811. fallbacks.addFallback(0, "BONES4");
  18812. }
  18813. //Attributes
  18814. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18815. if (this._defines.NORMAL) {
  18816. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18817. }
  18818. if (this._defines.UV1) {
  18819. attribs.push(BABYLON.VertexBuffer.UVKind);
  18820. }
  18821. if (this._defines.UV2) {
  18822. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18823. }
  18824. if (this._defines.VERTEXCOLOR) {
  18825. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18826. }
  18827. if (this._defines.BONES) {
  18828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18830. }
  18831. if (this._defines.INSTANCES) {
  18832. attribs.push("world0");
  18833. attribs.push("world1");
  18834. attribs.push("world2");
  18835. attribs.push("world3");
  18836. }
  18837. // Legacy browser patch
  18838. var shaderName = "default";
  18839. if (!scene.getEngine().getCaps().standardDerivatives) {
  18840. shaderName = "legacydefault";
  18841. }
  18842. var join = this._defines.toString();
  18843. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18844. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18845. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18846. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18847. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18848. "vFogInfos", "vFogColor", "pointSize",
  18849. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18850. "mBones",
  18851. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18852. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18853. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18854. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18855. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18856. ], join, fallbacks, this.onCompiled, this.onError);
  18857. }
  18858. if (!this._effect.isReady()) {
  18859. return false;
  18860. }
  18861. this._renderId = scene.getRenderId();
  18862. this._wasPreviouslyReady = true;
  18863. if (mesh) {
  18864. if (!mesh._materialDefines) {
  18865. mesh._materialDefines = new StandardMaterialDefines();
  18866. }
  18867. this._defines.cloneTo(mesh._materialDefines);
  18868. }
  18869. return true;
  18870. };
  18871. StandardMaterial.prototype.unbind = function () {
  18872. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18873. this._effect.setTexture("reflection2DSampler", null);
  18874. }
  18875. _super.prototype.unbind.call(this);
  18876. };
  18877. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18878. this._effect.setMatrix("world", world);
  18879. };
  18880. StandardMaterial.prototype.bind = function (world, mesh) {
  18881. var scene = this.getScene();
  18882. // Matrices
  18883. this.bindOnlyWorldMatrix(world);
  18884. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18885. // Bones
  18886. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18887. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18888. }
  18889. if (scene.getCachedMaterial() !== this) {
  18890. if (StandardMaterial.FresnelEnabled) {
  18891. // Fresnel
  18892. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18893. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18894. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18895. }
  18896. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18897. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18898. }
  18899. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18900. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18901. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18902. }
  18903. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18904. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18905. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18906. }
  18907. }
  18908. // Textures
  18909. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18910. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18911. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18912. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18913. }
  18914. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18915. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18916. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18917. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18918. }
  18919. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18920. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18921. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18922. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18923. }
  18924. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18925. if (this.reflectionTexture.isCube) {
  18926. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18927. }
  18928. else {
  18929. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18930. }
  18931. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18932. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18933. }
  18934. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18935. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18936. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18937. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18938. }
  18939. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18940. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18941. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  18942. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18943. }
  18944. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18945. this._effect.setTexture("specularSampler", this.specularTexture);
  18946. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18947. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18948. }
  18949. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18950. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18951. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18952. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18953. }
  18954. // Clip plane
  18955. if (scene.clipPlane) {
  18956. var clipPlane = scene.clipPlane;
  18957. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18958. }
  18959. // Point size
  18960. if (this.pointsCloud) {
  18961. this._effect.setFloat("pointSize", this.pointSize);
  18962. }
  18963. // Colors
  18964. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18965. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18966. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18967. if (this._defines.SPECULARTERM) {
  18968. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  18969. }
  18970. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18971. }
  18972. // Diffuse
  18973. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  18974. // Lights
  18975. if (scene.lightsEnabled && !this.disableLighting) {
  18976. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  18977. }
  18978. // View
  18979. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18980. this._effect.setMatrix("view", scene.getViewMatrix());
  18981. }
  18982. // Fog
  18983. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18984. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18985. this._effect.setColor3("vFogColor", scene.fogColor);
  18986. }
  18987. _super.prototype.bind.call(this, world, mesh);
  18988. };
  18989. StandardMaterial.prototype.getAnimatables = function () {
  18990. var results = [];
  18991. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18992. results.push(this.diffuseTexture);
  18993. }
  18994. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18995. results.push(this.ambientTexture);
  18996. }
  18997. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18998. results.push(this.opacityTexture);
  18999. }
  19000. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19001. results.push(this.reflectionTexture);
  19002. }
  19003. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19004. results.push(this.emissiveTexture);
  19005. }
  19006. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19007. results.push(this.specularTexture);
  19008. }
  19009. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19010. results.push(this.bumpTexture);
  19011. }
  19012. return results;
  19013. };
  19014. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19015. if (this.diffuseTexture) {
  19016. this.diffuseTexture.dispose();
  19017. }
  19018. if (this.ambientTexture) {
  19019. this.ambientTexture.dispose();
  19020. }
  19021. if (this.opacityTexture) {
  19022. this.opacityTexture.dispose();
  19023. }
  19024. if (this.reflectionTexture) {
  19025. this.reflectionTexture.dispose();
  19026. }
  19027. if (this.emissiveTexture) {
  19028. this.emissiveTexture.dispose();
  19029. }
  19030. if (this.specularTexture) {
  19031. this.specularTexture.dispose();
  19032. }
  19033. if (this.bumpTexture) {
  19034. this.bumpTexture.dispose();
  19035. }
  19036. _super.prototype.dispose.call(this, forceDisposeEffect);
  19037. };
  19038. StandardMaterial.prototype.clone = function (name) {
  19039. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19040. // Base material
  19041. this.copyTo(newStandardMaterial);
  19042. // Standard material
  19043. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19044. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19045. }
  19046. if (this.ambientTexture && this.ambientTexture.clone) {
  19047. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19048. }
  19049. if (this.opacityTexture && this.opacityTexture.clone) {
  19050. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19051. }
  19052. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19053. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19054. }
  19055. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19056. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19057. }
  19058. if (this.specularTexture && this.specularTexture.clone) {
  19059. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19060. }
  19061. if (this.bumpTexture && this.bumpTexture.clone) {
  19062. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19063. }
  19064. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19065. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19066. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19067. }
  19068. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19069. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19070. newStandardMaterial.specularColor = this.specularColor.clone();
  19071. newStandardMaterial.specularPower = this.specularPower;
  19072. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19073. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19074. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19075. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19076. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19077. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19078. newStandardMaterial.roughness = this.roughness;
  19079. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19080. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19081. }
  19082. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19083. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19084. }
  19085. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19086. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19087. }
  19088. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19089. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19090. }
  19091. return newStandardMaterial;
  19092. };
  19093. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19094. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19095. // Statics
  19096. // Flags used to enable or disable a type of texture for all Standard Materials
  19097. StandardMaterial.DiffuseTextureEnabled = true;
  19098. StandardMaterial.AmbientTextureEnabled = true;
  19099. StandardMaterial.OpacityTextureEnabled = true;
  19100. StandardMaterial.ReflectionTextureEnabled = true;
  19101. StandardMaterial.EmissiveTextureEnabled = true;
  19102. StandardMaterial.SpecularTextureEnabled = true;
  19103. StandardMaterial.BumpTextureEnabled = true;
  19104. StandardMaterial.FresnelEnabled = true;
  19105. StandardMaterial.LightmapEnabled = true;
  19106. return StandardMaterial;
  19107. })(BABYLON.Material);
  19108. BABYLON.StandardMaterial = StandardMaterial;
  19109. })(BABYLON || (BABYLON = {}));
  19110. var BABYLON;
  19111. (function (BABYLON) {
  19112. var MultiMaterial = (function (_super) {
  19113. __extends(MultiMaterial, _super);
  19114. function MultiMaterial(name, scene) {
  19115. _super.call(this, name, scene, true);
  19116. this.subMaterials = new Array();
  19117. scene.multiMaterials.push(this);
  19118. }
  19119. // Properties
  19120. MultiMaterial.prototype.getSubMaterial = function (index) {
  19121. if (index < 0 || index >= this.subMaterials.length) {
  19122. return this.getScene().defaultMaterial;
  19123. }
  19124. return this.subMaterials[index];
  19125. };
  19126. // Methods
  19127. MultiMaterial.prototype.isReady = function (mesh) {
  19128. for (var index = 0; index < this.subMaterials.length; index++) {
  19129. var subMaterial = this.subMaterials[index];
  19130. if (subMaterial) {
  19131. if (!this.subMaterials[index].isReady(mesh)) {
  19132. return false;
  19133. }
  19134. }
  19135. }
  19136. return true;
  19137. };
  19138. MultiMaterial.prototype.clone = function (name) {
  19139. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19140. for (var index = 0; index < this.subMaterials.length; index++) {
  19141. var subMaterial = this.subMaterials[index];
  19142. newMultiMaterial.subMaterials.push(subMaterial);
  19143. }
  19144. return newMultiMaterial;
  19145. };
  19146. return MultiMaterial;
  19147. })(BABYLON.Material);
  19148. BABYLON.MultiMaterial = MultiMaterial;
  19149. })(BABYLON || (BABYLON = {}));
  19150. var BABYLON;
  19151. (function (BABYLON) {
  19152. var SceneLoader = (function () {
  19153. function SceneLoader() {
  19154. }
  19155. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19156. get: function () {
  19157. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19158. },
  19159. set: function (value) {
  19160. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19161. },
  19162. enumerable: true,
  19163. configurable: true
  19164. });
  19165. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19166. get: function () {
  19167. return SceneLoader._ShowLoadingScreen;
  19168. },
  19169. set: function (value) {
  19170. SceneLoader._ShowLoadingScreen = value;
  19171. },
  19172. enumerable: true,
  19173. configurable: true
  19174. });
  19175. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19176. var dotPosition = sceneFilename.lastIndexOf(".");
  19177. var queryStringPosition = sceneFilename.indexOf("?");
  19178. if (queryStringPosition === -1) {
  19179. queryStringPosition = sceneFilename.length;
  19180. }
  19181. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19182. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19183. var plugin = this._registeredPlugins[index];
  19184. if (plugin.extensions.indexOf(extension) !== -1) {
  19185. return plugin;
  19186. }
  19187. }
  19188. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19189. };
  19190. // Public functions
  19191. SceneLoader.RegisterPlugin = function (plugin) {
  19192. plugin.extensions = plugin.extensions.toLowerCase();
  19193. SceneLoader._registeredPlugins.push(plugin);
  19194. };
  19195. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19196. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19197. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19198. return;
  19199. }
  19200. var loadingToken = {};
  19201. scene._addPendingData(loadingToken);
  19202. var manifestChecked = function (success) {
  19203. scene.database = database;
  19204. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19205. var importMeshFromData = function (data) {
  19206. var meshes = [];
  19207. var particleSystems = [];
  19208. var skeletons = [];
  19209. try {
  19210. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19211. if (onerror) {
  19212. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19213. }
  19214. scene._removePendingData(loadingToken);
  19215. return;
  19216. }
  19217. }
  19218. catch (e) {
  19219. if (onerror) {
  19220. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19221. }
  19222. scene._removePendingData(loadingToken);
  19223. return;
  19224. }
  19225. if (onsuccess) {
  19226. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19227. onsuccess(meshes, particleSystems, skeletons);
  19228. scene._removePendingData(loadingToken);
  19229. }
  19230. };
  19231. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19232. // Direct load
  19233. importMeshFromData(sceneFilename.substr(5));
  19234. return;
  19235. }
  19236. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19237. importMeshFromData(data);
  19238. }, progressCallBack, database);
  19239. };
  19240. if (scene.getEngine().enableOfflineSupport) {
  19241. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19242. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19243. }
  19244. else {
  19245. manifestChecked(true);
  19246. }
  19247. };
  19248. /**
  19249. * Load a scene
  19250. * @param rootUrl a string that defines the root url for scene and resources
  19251. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19252. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19253. */
  19254. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19255. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19256. };
  19257. /**
  19258. * Append a scene
  19259. * @param rootUrl a string that defines the root url for scene and resources
  19260. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19261. * @param scene is the instance of BABYLON.Scene to append to
  19262. */
  19263. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19264. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19265. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19266. return;
  19267. }
  19268. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19269. var database;
  19270. var loadingToken = {};
  19271. scene._addPendingData(loadingToken);
  19272. if (SceneLoader.ShowLoadingScreen) {
  19273. scene.getEngine().displayLoadingUI();
  19274. }
  19275. var loadSceneFromData = function (data) {
  19276. scene.database = database;
  19277. if (!plugin.load(scene, data, rootUrl)) {
  19278. if (onerror) {
  19279. onerror(scene);
  19280. }
  19281. scene._removePendingData(loadingToken);
  19282. scene.getEngine().hideLoadingUI();
  19283. return;
  19284. }
  19285. if (onsuccess) {
  19286. onsuccess(scene);
  19287. }
  19288. scene._removePendingData(loadingToken);
  19289. if (SceneLoader.ShowLoadingScreen) {
  19290. scene.executeWhenReady(function () {
  19291. scene.getEngine().hideLoadingUI();
  19292. });
  19293. }
  19294. };
  19295. var manifestChecked = function (success) {
  19296. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19297. };
  19298. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19299. // Direct load
  19300. loadSceneFromData(sceneFilename.substr(5));
  19301. return;
  19302. }
  19303. if (rootUrl.indexOf("file:") === -1) {
  19304. if (scene.getEngine().enableOfflineSupport) {
  19305. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19306. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19307. }
  19308. else {
  19309. manifestChecked(true);
  19310. }
  19311. }
  19312. else {
  19313. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19314. }
  19315. };
  19316. // Flags
  19317. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19318. SceneLoader._ShowLoadingScreen = true;
  19319. // Members
  19320. SceneLoader._registeredPlugins = new Array();
  19321. return SceneLoader;
  19322. })();
  19323. BABYLON.SceneLoader = SceneLoader;
  19324. ;
  19325. })(BABYLON || (BABYLON = {}));
  19326. var BABYLON;
  19327. (function (BABYLON) {
  19328. var Internals;
  19329. (function (Internals) {
  19330. var checkColors4 = function (colors, count) {
  19331. // Check if color3 was used
  19332. if (colors.length === count * 3) {
  19333. var colors4 = [];
  19334. for (var index = 0; index < colors.length; index += 3) {
  19335. var newIndex = (index / 3) * 4;
  19336. colors4[newIndex] = colors[index];
  19337. colors4[newIndex + 1] = colors[index + 1];
  19338. colors4[newIndex + 2] = colors[index + 2];
  19339. colors4[newIndex + 3] = 1.0;
  19340. }
  19341. return colors4;
  19342. }
  19343. return colors;
  19344. };
  19345. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19346. var texture = null;
  19347. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19348. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19349. texture.name = parsedTexture.name;
  19350. texture.hasAlpha = parsedTexture.hasAlpha;
  19351. texture.level = parsedTexture.level;
  19352. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19353. }
  19354. return texture;
  19355. };
  19356. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19357. if (parsedTexture.isCube) {
  19358. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19359. }
  19360. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19361. return null;
  19362. }
  19363. var texture;
  19364. if (parsedTexture.mirrorPlane) {
  19365. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19366. texture._waitingRenderList = parsedTexture.renderList;
  19367. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19368. }
  19369. else if (parsedTexture.isRenderTarget) {
  19370. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19371. texture._waitingRenderList = parsedTexture.renderList;
  19372. }
  19373. else {
  19374. if (parsedTexture.base64String) {
  19375. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19376. }
  19377. else {
  19378. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19379. }
  19380. }
  19381. texture.name = parsedTexture.name;
  19382. texture.hasAlpha = parsedTexture.hasAlpha;
  19383. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19384. texture.level = parsedTexture.level;
  19385. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19386. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19387. texture.uOffset = parsedTexture.uOffset;
  19388. texture.vOffset = parsedTexture.vOffset;
  19389. texture.uScale = parsedTexture.uScale;
  19390. texture.vScale = parsedTexture.vScale;
  19391. texture.uAng = parsedTexture.uAng;
  19392. texture.vAng = parsedTexture.vAng;
  19393. texture.wAng = parsedTexture.wAng;
  19394. texture.wrapU = parsedTexture.wrapU;
  19395. texture.wrapV = parsedTexture.wrapV;
  19396. // Animations
  19397. if (parsedTexture.animations) {
  19398. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19399. var parsedAnimation = parsedTexture.animations[animationIndex];
  19400. texture.animations.push(parseAnimation(parsedAnimation));
  19401. }
  19402. }
  19403. return texture;
  19404. };
  19405. var parseSkeleton = function (parsedSkeleton, scene) {
  19406. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19407. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19408. var parsedBone = parsedSkeleton.bones[index];
  19409. var parentBone = null;
  19410. if (parsedBone.parentBoneIndex > -1) {
  19411. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19412. }
  19413. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19414. if (parsedBone.animation) {
  19415. bone.animations.push(parseAnimation(parsedBone.animation));
  19416. }
  19417. }
  19418. return skeleton;
  19419. };
  19420. var parseFresnelParameters = function (parsedFresnelParameters) {
  19421. var fresnelParameters = new BABYLON.FresnelParameters();
  19422. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19423. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19424. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19425. fresnelParameters.bias = parsedFresnelParameters.bias;
  19426. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19427. return fresnelParameters;
  19428. };
  19429. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19430. var material;
  19431. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19432. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19433. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19434. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19435. material.specularPower = parsedMaterial.specularPower;
  19436. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19437. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19438. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19439. material.alpha = parsedMaterial.alpha;
  19440. material.id = parsedMaterial.id;
  19441. if (parsedMaterial.disableDepthWrite) {
  19442. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19443. }
  19444. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19445. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19446. material.wireframe = parsedMaterial.wireframe;
  19447. if (parsedMaterial.diffuseTexture) {
  19448. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19449. }
  19450. if (parsedMaterial.diffuseFresnelParameters) {
  19451. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19452. }
  19453. if (parsedMaterial.ambientTexture) {
  19454. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19455. }
  19456. if (parsedMaterial.opacityTexture) {
  19457. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19458. }
  19459. if (parsedMaterial.opacityFresnelParameters) {
  19460. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19461. }
  19462. if (parsedMaterial.reflectionTexture) {
  19463. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19464. }
  19465. if (parsedMaterial.reflectionFresnelParameters) {
  19466. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19467. }
  19468. if (parsedMaterial.emissiveTexture) {
  19469. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19470. }
  19471. if (parsedMaterial.lightmapTexture) {
  19472. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19473. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19474. }
  19475. if (parsedMaterial.emissiveFresnelParameters) {
  19476. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19477. }
  19478. if (parsedMaterial.specularTexture) {
  19479. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19480. }
  19481. if (parsedMaterial.bumpTexture) {
  19482. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19483. }
  19484. if (parsedMaterial.checkReadyOnlyOnce) {
  19485. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19486. }
  19487. return material;
  19488. };
  19489. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19490. for (var index = 0; index < parsedData.materials.length; index++) {
  19491. var parsedMaterial = parsedData.materials[index];
  19492. if (parsedMaterial.id === id) {
  19493. return parseMaterial(parsedMaterial, scene, rootUrl);
  19494. }
  19495. }
  19496. return null;
  19497. };
  19498. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19499. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19500. multiMaterial.id = parsedMultiMaterial.id;
  19501. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19502. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19503. var subMatId = parsedMultiMaterial.materials[matIndex];
  19504. if (subMatId) {
  19505. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19506. }
  19507. else {
  19508. multiMaterial.subMaterials.push(null);
  19509. }
  19510. }
  19511. return multiMaterial;
  19512. };
  19513. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19514. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19515. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19516. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19517. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19518. var parsedFlare = parsedLensFlareSystem.flares[index];
  19519. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19520. }
  19521. return lensFlareSystem;
  19522. };
  19523. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19524. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19525. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19526. if (parsedParticleSystem.textureName) {
  19527. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19528. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19529. }
  19530. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19531. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19532. particleSystem.minSize = parsedParticleSystem.minSize;
  19533. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19534. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19535. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19536. particleSystem.emitter = emitter;
  19537. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19538. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19539. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19540. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19541. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19542. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19543. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19544. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19545. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19546. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19547. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19548. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19549. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19550. particleSystem.start();
  19551. return particleSystem;
  19552. };
  19553. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19554. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19555. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19556. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19557. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19558. shadowGenerator.getShadowMap().renderList.push(mesh);
  19559. }
  19560. if (parsedShadowGenerator.usePoissonSampling) {
  19561. shadowGenerator.usePoissonSampling = true;
  19562. }
  19563. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19564. shadowGenerator.useVarianceShadowMap = true;
  19565. }
  19566. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19567. shadowGenerator.useBlurVarianceShadowMap = true;
  19568. if (parsedShadowGenerator.blurScale) {
  19569. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19570. }
  19571. if (parsedShadowGenerator.blurBoxOffset) {
  19572. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19573. }
  19574. }
  19575. if (parsedShadowGenerator.bias !== undefined) {
  19576. shadowGenerator.bias = parsedShadowGenerator.bias;
  19577. }
  19578. return shadowGenerator;
  19579. };
  19580. var parseAnimation = function (parsedAnimation) {
  19581. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19582. var dataType = parsedAnimation.dataType;
  19583. var keys = [];
  19584. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19585. var key = parsedAnimation.keys[index];
  19586. var data;
  19587. switch (dataType) {
  19588. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19589. data = key.values[0];
  19590. break;
  19591. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19592. data = BABYLON.Quaternion.FromArray(key.values);
  19593. break;
  19594. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19595. data = BABYLON.Matrix.FromArray(key.values);
  19596. break;
  19597. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19598. default:
  19599. data = BABYLON.Vector3.FromArray(key.values);
  19600. break;
  19601. }
  19602. keys.push({
  19603. frame: key.frame,
  19604. value: data
  19605. });
  19606. }
  19607. animation.setKeys(keys);
  19608. return animation;
  19609. };
  19610. var parseLight = function (parsedLight, scene) {
  19611. var light;
  19612. switch (parsedLight.type) {
  19613. case 0:
  19614. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19615. break;
  19616. case 1:
  19617. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19618. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19619. break;
  19620. case 2:
  19621. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19622. break;
  19623. case 3:
  19624. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19625. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19626. break;
  19627. }
  19628. light.id = parsedLight.id;
  19629. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19630. if (parsedLight.intensity !== undefined) {
  19631. light.intensity = parsedLight.intensity;
  19632. }
  19633. if (parsedLight.range) {
  19634. light.range = parsedLight.range;
  19635. }
  19636. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19637. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19638. if (parsedLight.excludedMeshesIds) {
  19639. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19640. }
  19641. // Parent
  19642. if (parsedLight.parentId) {
  19643. light._waitingParentId = parsedLight.parentId;
  19644. }
  19645. if (parsedLight.includedOnlyMeshesIds) {
  19646. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19647. }
  19648. // Animations
  19649. if (parsedLight.animations) {
  19650. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19651. var parsedAnimation = parsedLight.animations[animationIndex];
  19652. light.animations.push(parseAnimation(parsedAnimation));
  19653. }
  19654. }
  19655. if (parsedLight.autoAnimate) {
  19656. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19657. }
  19658. };
  19659. var parseCamera = function (parsedCamera, scene) {
  19660. var camera;
  19661. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19662. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19663. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19664. var alpha = parsedCamera.alpha;
  19665. var beta = parsedCamera.beta;
  19666. var radius = parsedCamera.radius;
  19667. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19668. var interaxial_distance = parsedCamera.interaxial_distance;
  19669. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19670. }
  19671. else {
  19672. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19673. }
  19674. }
  19675. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19676. interaxial_distance = parsedCamera.interaxial_distance;
  19677. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19678. }
  19679. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19680. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19681. }
  19682. else if (parsedCamera.type === "FollowCamera") {
  19683. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19684. camera.heightOffset = parsedCamera.heightOffset;
  19685. camera.radius = parsedCamera.radius;
  19686. camera.rotationOffset = parsedCamera.rotationOffset;
  19687. if (lockedTargetMesh)
  19688. camera.target = lockedTargetMesh;
  19689. }
  19690. else if (parsedCamera.type === "GamepadCamera") {
  19691. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19692. }
  19693. else if (parsedCamera.type === "TouchCamera") {
  19694. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19695. }
  19696. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19697. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19698. }
  19699. else if (parsedCamera.type === "WebVRFreeCamera") {
  19700. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19701. }
  19702. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19703. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19704. }
  19705. else {
  19706. // Free Camera is the default value
  19707. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19708. }
  19709. // apply 3d rig, when found
  19710. if (parsedCamera.cameraRigMode) {
  19711. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19712. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19713. }
  19714. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19715. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19716. camera.lockedTarget = lockedTargetMesh;
  19717. }
  19718. camera.id = parsedCamera.id;
  19719. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19720. // Parent
  19721. if (parsedCamera.parentId) {
  19722. camera._waitingParentId = parsedCamera.parentId;
  19723. }
  19724. // Target
  19725. if (parsedCamera.target) {
  19726. if (camera.setTarget) {
  19727. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19728. }
  19729. else {
  19730. //For ArcRotate
  19731. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19732. }
  19733. }
  19734. else {
  19735. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19736. }
  19737. camera.fov = parsedCamera.fov;
  19738. camera.minZ = parsedCamera.minZ;
  19739. camera.maxZ = parsedCamera.maxZ;
  19740. camera.speed = parsedCamera.speed;
  19741. camera.inertia = parsedCamera.inertia;
  19742. camera.checkCollisions = parsedCamera.checkCollisions;
  19743. camera.applyGravity = parsedCamera.applyGravity;
  19744. if (parsedCamera.ellipsoid) {
  19745. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19746. }
  19747. // Animations
  19748. if (parsedCamera.animations) {
  19749. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19750. var parsedAnimation = parsedCamera.animations[animationIndex];
  19751. camera.animations.push(parseAnimation(parsedAnimation));
  19752. }
  19753. }
  19754. if (parsedCamera.autoAnimate) {
  19755. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19756. }
  19757. // Layer Mask
  19758. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19759. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19760. }
  19761. else {
  19762. camera.layerMask = 0x0FFFFFFF;
  19763. }
  19764. return camera;
  19765. };
  19766. var parseGeometry = function (parsedGeometry, scene) {
  19767. var id = parsedGeometry.id;
  19768. return scene.getGeometryByID(id);
  19769. };
  19770. var parseBox = function (parsedBox, scene) {
  19771. if (parseGeometry(parsedBox, scene)) {
  19772. return null; // null since geometry could be something else than a box...
  19773. }
  19774. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19775. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19776. scene.pushGeometry(box, true);
  19777. return box;
  19778. };
  19779. var parseSphere = function (parsedSphere, scene) {
  19780. if (parseGeometry(parsedSphere, scene)) {
  19781. return null; // null since geometry could be something else than a sphere...
  19782. }
  19783. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19784. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19785. scene.pushGeometry(sphere, true);
  19786. return sphere;
  19787. };
  19788. var parseCylinder = function (parsedCylinder, scene) {
  19789. if (parseGeometry(parsedCylinder, scene)) {
  19790. return null; // null since geometry could be something else than a cylinder...
  19791. }
  19792. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19793. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19794. scene.pushGeometry(cylinder, true);
  19795. return cylinder;
  19796. };
  19797. var parseTorus = function (parsedTorus, scene) {
  19798. if (parseGeometry(parsedTorus, scene)) {
  19799. return null; // null since geometry could be something else than a torus...
  19800. }
  19801. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19802. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19803. scene.pushGeometry(torus, true);
  19804. return torus;
  19805. };
  19806. var parseGround = function (parsedGround, scene) {
  19807. if (parseGeometry(parsedGround, scene)) {
  19808. return null; // null since geometry could be something else than a ground...
  19809. }
  19810. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19811. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19812. scene.pushGeometry(ground, true);
  19813. return ground;
  19814. };
  19815. var parsePlane = function (parsedPlane, scene) {
  19816. if (parseGeometry(parsedPlane, scene)) {
  19817. return null; // null since geometry could be something else than a plane...
  19818. }
  19819. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19820. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19821. scene.pushGeometry(plane, true);
  19822. return plane;
  19823. };
  19824. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19825. if (parseGeometry(parsedTorusKnot, scene)) {
  19826. return null; // null since geometry could be something else than a torusKnot...
  19827. }
  19828. 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);
  19829. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19830. scene.pushGeometry(torusKnot, true);
  19831. return torusKnot;
  19832. };
  19833. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19834. if (parseGeometry(parsedVertexData, scene)) {
  19835. return null; // null since geometry could be a primitive
  19836. }
  19837. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19838. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19839. if (parsedVertexData.delayLoadingFile) {
  19840. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19841. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19842. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19843. geometry._delayInfo = [];
  19844. if (parsedVertexData.hasUVs) {
  19845. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19846. }
  19847. if (parsedVertexData.hasUVs2) {
  19848. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19849. }
  19850. if (parsedVertexData.hasUVs3) {
  19851. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19852. }
  19853. if (parsedVertexData.hasUVs4) {
  19854. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19855. }
  19856. if (parsedVertexData.hasUVs5) {
  19857. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19858. }
  19859. if (parsedVertexData.hasUVs6) {
  19860. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19861. }
  19862. if (parsedVertexData.hasColors) {
  19863. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19864. }
  19865. if (parsedVertexData.hasMatricesIndices) {
  19866. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19867. }
  19868. if (parsedVertexData.hasMatricesWeights) {
  19869. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19870. }
  19871. geometry._delayLoadingFunction = importVertexData;
  19872. }
  19873. else {
  19874. importVertexData(parsedVertexData, geometry);
  19875. }
  19876. scene.pushGeometry(geometry, true);
  19877. return geometry;
  19878. };
  19879. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19880. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19881. mesh.id = parsedMesh.id;
  19882. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19883. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19884. if (parsedMesh.rotationQuaternion) {
  19885. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19886. }
  19887. else if (parsedMesh.rotation) {
  19888. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19889. }
  19890. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19891. if (parsedMesh.localMatrix) {
  19892. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19893. }
  19894. else if (parsedMesh.pivotMatrix) {
  19895. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19896. }
  19897. mesh.setEnabled(parsedMesh.isEnabled);
  19898. mesh.isVisible = parsedMesh.isVisible;
  19899. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19900. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19901. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19902. if (parsedMesh.applyFog !== undefined) {
  19903. mesh.applyFog = parsedMesh.applyFog;
  19904. }
  19905. if (parsedMesh.pickable !== undefined) {
  19906. mesh.isPickable = parsedMesh.pickable;
  19907. }
  19908. if (parsedMesh.alphaIndex !== undefined) {
  19909. mesh.alphaIndex = parsedMesh.alphaIndex;
  19910. }
  19911. mesh.receiveShadows = parsedMesh.receiveShadows;
  19912. mesh.billboardMode = parsedMesh.billboardMode;
  19913. if (parsedMesh.visibility !== undefined) {
  19914. mesh.visibility = parsedMesh.visibility;
  19915. }
  19916. mesh.checkCollisions = parsedMesh.checkCollisions;
  19917. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19918. // freezeWorldMatrix
  19919. if (parsedMesh.freezeWorldMatrix) {
  19920. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19921. }
  19922. // Parent
  19923. if (parsedMesh.parentId) {
  19924. mesh._waitingParentId = parsedMesh.parentId;
  19925. }
  19926. // Actions
  19927. if (parsedMesh.actions !== undefined) {
  19928. mesh._waitingActions = parsedMesh.actions;
  19929. }
  19930. // Geometry
  19931. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19932. if (parsedMesh.delayLoadingFile) {
  19933. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19934. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19935. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19936. if (parsedMesh._binaryInfo) {
  19937. mesh._binaryInfo = parsedMesh._binaryInfo;
  19938. }
  19939. mesh._delayInfo = [];
  19940. if (parsedMesh.hasUVs) {
  19941. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19942. }
  19943. if (parsedMesh.hasUVs2) {
  19944. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19945. }
  19946. if (parsedMesh.hasUVs3) {
  19947. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19948. }
  19949. if (parsedMesh.hasUVs4) {
  19950. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19951. }
  19952. if (parsedMesh.hasUVs5) {
  19953. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19954. }
  19955. if (parsedMesh.hasUVs6) {
  19956. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19957. }
  19958. if (parsedMesh.hasColors) {
  19959. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19960. }
  19961. if (parsedMesh.hasMatricesIndices) {
  19962. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19963. }
  19964. if (parsedMesh.hasMatricesWeights) {
  19965. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19966. }
  19967. mesh._delayLoadingFunction = importGeometry;
  19968. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19969. mesh._checkDelayState();
  19970. }
  19971. }
  19972. else {
  19973. importGeometry(parsedMesh, mesh);
  19974. }
  19975. // Material
  19976. if (parsedMesh.materialId) {
  19977. mesh.setMaterialByID(parsedMesh.materialId);
  19978. }
  19979. else {
  19980. mesh.material = null;
  19981. }
  19982. // Skeleton
  19983. if (parsedMesh.skeletonId > -1) {
  19984. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19985. if (parsedMesh.numBoneInfluencers) {
  19986. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19987. }
  19988. }
  19989. // Physics
  19990. if (parsedMesh.physicsImpostor) {
  19991. if (!scene.isPhysicsEnabled()) {
  19992. scene.enablePhysics();
  19993. }
  19994. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19995. }
  19996. // Animations
  19997. if (parsedMesh.animations) {
  19998. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19999. var parsedAnimation = parsedMesh.animations[animationIndex];
  20000. mesh.animations.push(parseAnimation(parsedAnimation));
  20001. }
  20002. }
  20003. if (parsedMesh.autoAnimate) {
  20004. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20005. }
  20006. // Layer Mask
  20007. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20008. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20009. }
  20010. else {
  20011. mesh.layerMask = 0x0FFFFFFF;
  20012. }
  20013. // Instances
  20014. if (parsedMesh.instances) {
  20015. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20016. var parsedInstance = parsedMesh.instances[index];
  20017. var instance = mesh.createInstance(parsedInstance.name);
  20018. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20019. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20020. if (parsedInstance.rotationQuaternion) {
  20021. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20022. }
  20023. else if (parsedInstance.rotation) {
  20024. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20025. }
  20026. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20027. instance.checkCollisions = mesh.checkCollisions;
  20028. if (parsedMesh.animations) {
  20029. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20030. parsedAnimation = parsedMesh.animations[animationIndex];
  20031. instance.animations.push(parseAnimation(parsedAnimation));
  20032. }
  20033. }
  20034. }
  20035. }
  20036. return mesh;
  20037. };
  20038. var parseActions = function (parsedActions, object, scene) {
  20039. var actionManager = new BABYLON.ActionManager(scene);
  20040. if (object === null)
  20041. scene.actionManager = actionManager;
  20042. else
  20043. object.actionManager = actionManager;
  20044. // instanciate a new object
  20045. var instanciate = function (name, params) {
  20046. var newInstance = Object.create(BABYLON[name].prototype);
  20047. newInstance.constructor.apply(newInstance, params);
  20048. return newInstance;
  20049. };
  20050. var parseParameter = function (name, value, target, propertyPath) {
  20051. if (propertyPath === null) {
  20052. // String, boolean or float
  20053. var floatValue = parseFloat(value);
  20054. if (value === "true" || value === "false")
  20055. return value === "true";
  20056. else
  20057. return isNaN(floatValue) ? value : floatValue;
  20058. }
  20059. var effectiveTarget = propertyPath.split(".");
  20060. var values = value.split(",");
  20061. // Get effective Target
  20062. for (var i = 0; i < effectiveTarget.length; i++) {
  20063. target = target[effectiveTarget[i]];
  20064. }
  20065. // Return appropriate value with its type
  20066. if (typeof (target) === "boolean")
  20067. return values[0] === "true";
  20068. if (typeof (target) === "string")
  20069. return values[0];
  20070. // Parameters with multiple values such as Vector3 etc.
  20071. var split = new Array();
  20072. for (var i = 0; i < values.length; i++)
  20073. split.push(parseFloat(values[i]));
  20074. if (target instanceof BABYLON.Vector3)
  20075. return BABYLON.Vector3.FromArray(split);
  20076. if (target instanceof BABYLON.Vector4)
  20077. return BABYLON.Vector4.FromArray(split);
  20078. if (target instanceof BABYLON.Color3)
  20079. return BABYLON.Color3.FromArray(split);
  20080. if (target instanceof BABYLON.Color4)
  20081. return BABYLON.Color4.FromArray(split);
  20082. return parseFloat(values[0]);
  20083. };
  20084. // traverse graph per trigger
  20085. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20086. if (combineArray === void 0) { combineArray = null; }
  20087. if (parsedAction.detached)
  20088. return;
  20089. var parameters = new Array();
  20090. var target = null;
  20091. var propertyPath = null;
  20092. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20093. // Parameters
  20094. if (parsedAction.type === 2)
  20095. parameters.push(actionManager);
  20096. else
  20097. parameters.push(trigger);
  20098. if (combine) {
  20099. var actions = new Array();
  20100. for (var j = 0; j < parsedAction.combine.length; j++) {
  20101. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20102. }
  20103. parameters.push(actions);
  20104. }
  20105. else {
  20106. for (var i = 0; i < parsedAction.properties.length; i++) {
  20107. var value = parsedAction.properties[i].value;
  20108. var name = parsedAction.properties[i].name;
  20109. var targetType = parsedAction.properties[i].targetType;
  20110. if (name === "target")
  20111. if (targetType !== null && targetType === "SceneProperties")
  20112. value = target = scene;
  20113. else
  20114. value = target = scene.getNodeByName(value);
  20115. else if (name === "parent")
  20116. value = scene.getNodeByName(value);
  20117. else if (name === "sound")
  20118. value = scene.getSoundByName(value);
  20119. else if (name !== "propertyPath") {
  20120. if (parsedAction.type === 2 && name === "operator")
  20121. value = BABYLON.ValueCondition[value];
  20122. else
  20123. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20124. }
  20125. else {
  20126. propertyPath = value;
  20127. }
  20128. parameters.push(value);
  20129. }
  20130. }
  20131. if (combineArray === null) {
  20132. parameters.push(condition);
  20133. }
  20134. else {
  20135. parameters.push(null);
  20136. }
  20137. // If interpolate value action
  20138. if (parsedAction.name === "InterpolateValueAction") {
  20139. var param = parameters[parameters.length - 2];
  20140. parameters[parameters.length - 1] = param;
  20141. parameters[parameters.length - 2] = condition;
  20142. }
  20143. // Action or condition(s) and not CombineAction
  20144. var newAction = instanciate(parsedAction.name, parameters);
  20145. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20146. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20147. if (action)
  20148. action.then(nothing);
  20149. else
  20150. actionManager.registerAction(nothing);
  20151. action = nothing;
  20152. }
  20153. if (combineArray === null) {
  20154. if (newAction instanceof BABYLON.Condition) {
  20155. condition = newAction;
  20156. newAction = action;
  20157. }
  20158. else {
  20159. condition = null;
  20160. if (action)
  20161. action.then(newAction);
  20162. else
  20163. actionManager.registerAction(newAction);
  20164. }
  20165. }
  20166. else {
  20167. combineArray.push(newAction);
  20168. }
  20169. for (var i = 0; i < parsedAction.children.length; i++)
  20170. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20171. };
  20172. // triggers
  20173. for (var i = 0; i < parsedActions.children.length; i++) {
  20174. var triggerParams;
  20175. var trigger = parsedActions.children[i];
  20176. if (trigger.properties.length > 0) {
  20177. var param = trigger.properties[0].value;
  20178. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20179. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20180. }
  20181. else
  20182. triggerParams = BABYLON.ActionManager[trigger.name];
  20183. for (var j = 0; j < trigger.children.length; j++) {
  20184. if (!trigger.detached)
  20185. traverse(trigger.children[j], triggerParams, null, null);
  20186. }
  20187. }
  20188. };
  20189. var parseSound = function (parsedSound, scene, rootUrl) {
  20190. var soundName = parsedSound.name;
  20191. var soundUrl = rootUrl + soundName;
  20192. var options = {
  20193. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20194. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20195. rolloffFactor: parsedSound.rolloffFactor,
  20196. refDistance: parsedSound.refDistance,
  20197. distanceModel: parsedSound.distanceModel,
  20198. playbackRate: parsedSound.playbackRate
  20199. };
  20200. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20201. scene._addPendingData(newSound);
  20202. if (parsedSound.position) {
  20203. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20204. newSound.setPosition(soundPosition);
  20205. }
  20206. if (parsedSound.isDirectional) {
  20207. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20208. if (parsedSound.localDirectionToMesh) {
  20209. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20210. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20211. }
  20212. }
  20213. if (parsedSound.connectedMeshId) {
  20214. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20215. if (connectedMesh) {
  20216. newSound.attachToMesh(connectedMesh);
  20217. }
  20218. }
  20219. };
  20220. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20221. names = (names instanceof Array) ? names : [names];
  20222. for (var i in names) {
  20223. if (mesh.name === names[i]) {
  20224. hierarchyIds.push(mesh.id);
  20225. return true;
  20226. }
  20227. }
  20228. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20229. hierarchyIds.push(mesh.id);
  20230. return true;
  20231. }
  20232. return false;
  20233. };
  20234. var importVertexData = function (parsedVertexData, geometry) {
  20235. var vertexData = new BABYLON.VertexData();
  20236. // positions
  20237. var positions = parsedVertexData.positions;
  20238. if (positions) {
  20239. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20240. }
  20241. // normals
  20242. var normals = parsedVertexData.normals;
  20243. if (normals) {
  20244. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20245. }
  20246. // uvs
  20247. var uvs = parsedVertexData.uvs;
  20248. if (uvs) {
  20249. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20250. }
  20251. // uv2s
  20252. var uv2s = parsedVertexData.uv2s;
  20253. if (uv2s) {
  20254. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20255. }
  20256. // uv3s
  20257. var uv3s = parsedVertexData.uv3s;
  20258. if (uv3s) {
  20259. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20260. }
  20261. // uv4s
  20262. var uv4s = parsedVertexData.uv4s;
  20263. if (uv4s) {
  20264. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20265. }
  20266. // uv5s
  20267. var uv5s = parsedVertexData.uv5s;
  20268. if (uv5s) {
  20269. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20270. }
  20271. // uv6s
  20272. var uv6s = parsedVertexData.uv6s;
  20273. if (uv6s) {
  20274. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20275. }
  20276. // colors
  20277. var colors = parsedVertexData.colors;
  20278. if (colors) {
  20279. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20280. }
  20281. // matricesIndices
  20282. var matricesIndices = parsedVertexData.matricesIndices;
  20283. if (matricesIndices) {
  20284. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20285. }
  20286. // matricesWeights
  20287. var matricesWeights = parsedVertexData.matricesWeights;
  20288. if (matricesWeights) {
  20289. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20290. }
  20291. // indices
  20292. var indices = parsedVertexData.indices;
  20293. if (indices) {
  20294. vertexData.indices = indices;
  20295. }
  20296. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20297. };
  20298. var importGeometry = function (parsedGeometry, mesh) {
  20299. var scene = mesh.getScene();
  20300. // Geometry
  20301. var geometryId = parsedGeometry.geometryId;
  20302. if (geometryId) {
  20303. var geometry = scene.getGeometryByID(geometryId);
  20304. if (geometry) {
  20305. geometry.applyToMesh(mesh);
  20306. }
  20307. }
  20308. else if (parsedGeometry instanceof ArrayBuffer) {
  20309. var binaryInfo = mesh._binaryInfo;
  20310. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20311. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20312. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20313. }
  20314. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20315. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20316. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20317. }
  20318. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20319. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20320. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20321. }
  20322. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20323. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20324. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20325. }
  20326. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20327. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20328. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20329. }
  20330. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20331. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20332. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20333. }
  20334. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20335. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20336. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20337. }
  20338. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20339. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20340. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20341. }
  20342. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20343. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20344. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20345. }
  20346. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20347. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20348. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20349. }
  20350. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20351. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20352. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20353. }
  20354. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20355. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20356. mesh.setIndices(indicesData);
  20357. }
  20358. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20359. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20360. mesh.subMeshes = [];
  20361. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20362. var materialIndex = subMeshesData[(i * 5) + 0];
  20363. var verticesStart = subMeshesData[(i * 5) + 1];
  20364. var verticesCount = subMeshesData[(i * 5) + 2];
  20365. var indexStart = subMeshesData[(i * 5) + 3];
  20366. var indexCount = subMeshesData[(i * 5) + 4];
  20367. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20368. }
  20369. }
  20370. }
  20371. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20372. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20373. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20374. if (parsedGeometry.uvs) {
  20375. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20376. }
  20377. if (parsedGeometry.uvs2) {
  20378. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20379. }
  20380. if (parsedGeometry.uvs3) {
  20381. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20382. }
  20383. if (parsedGeometry.uvs4) {
  20384. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20385. }
  20386. if (parsedGeometry.uvs5) {
  20387. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20388. }
  20389. if (parsedGeometry.uvs6) {
  20390. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20391. }
  20392. if (parsedGeometry.colors) {
  20393. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20394. }
  20395. if (parsedGeometry.matricesIndices) {
  20396. if (!parsedGeometry.matricesIndices._isExpanded) {
  20397. var floatIndices = [];
  20398. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20399. var matricesIndex = parsedGeometry.matricesIndices[i];
  20400. floatIndices.push(matricesIndex & 0x000000FF);
  20401. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20402. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20403. floatIndices.push(matricesIndex >> 24);
  20404. }
  20405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20406. }
  20407. else {
  20408. delete parsedGeometry.matricesIndices._isExpanded;
  20409. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20410. }
  20411. }
  20412. if (parsedGeometry.matricesWeights) {
  20413. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20414. }
  20415. mesh.setIndices(parsedGeometry.indices);
  20416. }
  20417. // SubMeshes
  20418. if (parsedGeometry.subMeshes) {
  20419. mesh.subMeshes = [];
  20420. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20421. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20422. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20423. }
  20424. }
  20425. // Flat shading
  20426. if (mesh._shouldGenerateFlatShading) {
  20427. mesh.convertToFlatShadedMesh();
  20428. delete mesh._shouldGenerateFlatShading;
  20429. }
  20430. // Update
  20431. mesh.computeWorldMatrix(true);
  20432. // Octree
  20433. if (scene._selectionOctree) {
  20434. scene._selectionOctree.addMesh(mesh);
  20435. }
  20436. };
  20437. BABYLON.SceneLoader.RegisterPlugin({
  20438. extensions: ".babylon",
  20439. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20440. var parsedData = JSON.parse(data);
  20441. var loadedSkeletonsIds = [];
  20442. var loadedMaterialsIds = [];
  20443. var hierarchyIds = [];
  20444. for (var index = 0; index < parsedData.meshes.length; index++) {
  20445. var parsedMesh = parsedData.meshes[index];
  20446. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20447. if (meshesNames instanceof Array) {
  20448. // Remove found mesh name from list.
  20449. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20450. }
  20451. //Geometry?
  20452. if (parsedMesh.geometryId) {
  20453. //does the file contain geometries?
  20454. if (parsedData.geometries) {
  20455. //find the correct geometry and add it to the scene
  20456. var found = false;
  20457. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20458. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20459. return;
  20460. }
  20461. else {
  20462. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20463. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20464. switch (geometryType) {
  20465. case "boxes":
  20466. parseBox(parsedGeometryData, scene);
  20467. break;
  20468. case "spheres":
  20469. parseSphere(parsedGeometryData, scene);
  20470. break;
  20471. case "cylinders":
  20472. parseCylinder(parsedGeometryData, scene);
  20473. break;
  20474. case "toruses":
  20475. parseTorus(parsedGeometryData, scene);
  20476. break;
  20477. case "grounds":
  20478. parseGround(parsedGeometryData, scene);
  20479. break;
  20480. case "planes":
  20481. parsePlane(parsedGeometryData, scene);
  20482. break;
  20483. case "torusKnots":
  20484. parseTorusKnot(parsedGeometryData, scene);
  20485. break;
  20486. case "vertexData":
  20487. parseVertexData(parsedGeometryData, scene, rootUrl);
  20488. break;
  20489. }
  20490. found = true;
  20491. }
  20492. });
  20493. }
  20494. });
  20495. if (!found) {
  20496. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20497. }
  20498. }
  20499. }
  20500. // Material ?
  20501. if (parsedMesh.materialId) {
  20502. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20503. if (!materialFound && parsedData.multiMaterials) {
  20504. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20505. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20506. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20507. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20508. var subMatId = parsedMultiMaterial.materials[matIndex];
  20509. loadedMaterialsIds.push(subMatId);
  20510. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20511. }
  20512. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20513. parseMultiMaterial(parsedMultiMaterial, scene);
  20514. materialFound = true;
  20515. break;
  20516. }
  20517. }
  20518. }
  20519. if (!materialFound) {
  20520. loadedMaterialsIds.push(parsedMesh.materialId);
  20521. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20522. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20523. }
  20524. }
  20525. }
  20526. // Skeleton ?
  20527. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20528. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20529. if (!skeletonAlreadyLoaded) {
  20530. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20531. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20532. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20533. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20534. loadedSkeletonsIds.push(parsedSkeleton.id);
  20535. }
  20536. }
  20537. }
  20538. }
  20539. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20540. meshes.push(mesh);
  20541. }
  20542. }
  20543. // Connecting parents
  20544. for (index = 0; index < scene.meshes.length; index++) {
  20545. var currentMesh = scene.meshes[index];
  20546. if (currentMesh._waitingParentId) {
  20547. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20548. currentMesh._waitingParentId = undefined;
  20549. }
  20550. }
  20551. // freeze world matrix application
  20552. for (index = 0; index < scene.meshes.length; index++) {
  20553. var currentMesh = scene.meshes[index];
  20554. if (currentMesh._waitingFreezeWorldMatrix) {
  20555. currentMesh.freezeWorldMatrix();
  20556. currentMesh._waitingFreezeWorldMatrix = undefined;
  20557. }
  20558. }
  20559. // Particles
  20560. if (parsedData.particleSystems) {
  20561. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20562. var parsedParticleSystem = parsedData.particleSystems[index];
  20563. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20564. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20565. }
  20566. }
  20567. }
  20568. return true;
  20569. },
  20570. load: function (scene, data, rootUrl) {
  20571. var parsedData = JSON.parse(data);
  20572. // Scene
  20573. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20574. scene.autoClear = parsedData.autoClear;
  20575. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20576. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20577. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20578. // Fog
  20579. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20580. scene.fogMode = parsedData.fogMode;
  20581. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20582. scene.fogStart = parsedData.fogStart;
  20583. scene.fogEnd = parsedData.fogEnd;
  20584. scene.fogDensity = parsedData.fogDensity;
  20585. }
  20586. // Lights
  20587. for (var index = 0; index < parsedData.lights.length; index++) {
  20588. var parsedLight = parsedData.lights[index];
  20589. parseLight(parsedLight, scene);
  20590. }
  20591. // Materials
  20592. if (parsedData.materials) {
  20593. for (index = 0; index < parsedData.materials.length; index++) {
  20594. var parsedMaterial = parsedData.materials[index];
  20595. parseMaterial(parsedMaterial, scene, rootUrl);
  20596. }
  20597. }
  20598. if (parsedData.multiMaterials) {
  20599. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20600. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20601. parseMultiMaterial(parsedMultiMaterial, scene);
  20602. }
  20603. }
  20604. // Skeletons
  20605. if (parsedData.skeletons) {
  20606. for (index = 0; index < parsedData.skeletons.length; index++) {
  20607. var parsedSkeleton = parsedData.skeletons[index];
  20608. parseSkeleton(parsedSkeleton, scene);
  20609. }
  20610. }
  20611. // Geometries
  20612. var geometries = parsedData.geometries;
  20613. if (geometries) {
  20614. // Boxes
  20615. var boxes = geometries.boxes;
  20616. if (boxes) {
  20617. for (index = 0; index < boxes.length; index++) {
  20618. var parsedBox = boxes[index];
  20619. parseBox(parsedBox, scene);
  20620. }
  20621. }
  20622. // Spheres
  20623. var spheres = geometries.spheres;
  20624. if (spheres) {
  20625. for (index = 0; index < spheres.length; index++) {
  20626. var parsedSphere = spheres[index];
  20627. parseSphere(parsedSphere, scene);
  20628. }
  20629. }
  20630. // Cylinders
  20631. var cylinders = geometries.cylinders;
  20632. if (cylinders) {
  20633. for (index = 0; index < cylinders.length; index++) {
  20634. var parsedCylinder = cylinders[index];
  20635. parseCylinder(parsedCylinder, scene);
  20636. }
  20637. }
  20638. // Toruses
  20639. var toruses = geometries.toruses;
  20640. if (toruses) {
  20641. for (index = 0; index < toruses.length; index++) {
  20642. var parsedTorus = toruses[index];
  20643. parseTorus(parsedTorus, scene);
  20644. }
  20645. }
  20646. // Grounds
  20647. var grounds = geometries.grounds;
  20648. if (grounds) {
  20649. for (index = 0; index < grounds.length; index++) {
  20650. var parsedGround = grounds[index];
  20651. parseGround(parsedGround, scene);
  20652. }
  20653. }
  20654. // Planes
  20655. var planes = geometries.planes;
  20656. if (planes) {
  20657. for (index = 0; index < planes.length; index++) {
  20658. var parsedPlane = planes[index];
  20659. parsePlane(parsedPlane, scene);
  20660. }
  20661. }
  20662. // TorusKnots
  20663. var torusKnots = geometries.torusKnots;
  20664. if (torusKnots) {
  20665. for (index = 0; index < torusKnots.length; index++) {
  20666. var parsedTorusKnot = torusKnots[index];
  20667. parseTorusKnot(parsedTorusKnot, scene);
  20668. }
  20669. }
  20670. // VertexData
  20671. var vertexData = geometries.vertexData;
  20672. if (vertexData) {
  20673. for (index = 0; index < vertexData.length; index++) {
  20674. var parsedVertexData = vertexData[index];
  20675. parseVertexData(parsedVertexData, scene, rootUrl);
  20676. }
  20677. }
  20678. }
  20679. // Meshes
  20680. for (index = 0; index < parsedData.meshes.length; index++) {
  20681. var parsedMesh = parsedData.meshes[index];
  20682. parseMesh(parsedMesh, scene, rootUrl);
  20683. }
  20684. // Cameras
  20685. for (index = 0; index < parsedData.cameras.length; index++) {
  20686. var parsedCamera = parsedData.cameras[index];
  20687. parseCamera(parsedCamera, scene);
  20688. }
  20689. if (parsedData.activeCameraID) {
  20690. scene.setActiveCameraByID(parsedData.activeCameraID);
  20691. }
  20692. // Browsing all the graph to connect the dots
  20693. for (index = 0; index < scene.cameras.length; index++) {
  20694. var camera = scene.cameras[index];
  20695. if (camera._waitingParentId) {
  20696. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20697. camera._waitingParentId = undefined;
  20698. }
  20699. }
  20700. for (index = 0; index < scene.lights.length; index++) {
  20701. var light = scene.lights[index];
  20702. if (light._waitingParentId) {
  20703. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20704. light._waitingParentId = undefined;
  20705. }
  20706. }
  20707. // Sounds
  20708. if (BABYLON.AudioEngine && parsedData.sounds) {
  20709. for (index = 0; index < parsedData.sounds.length; index++) {
  20710. var parsedSound = parsedData.sounds[index];
  20711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20712. parseSound(parsedSound, scene, rootUrl);
  20713. }
  20714. else {
  20715. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20716. }
  20717. }
  20718. }
  20719. // Connect parents & children and parse actions
  20720. for (index = 0; index < scene.meshes.length; index++) {
  20721. var mesh = scene.meshes[index];
  20722. if (mesh._waitingParentId) {
  20723. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20724. mesh._waitingParentId = undefined;
  20725. }
  20726. if (mesh._waitingActions) {
  20727. parseActions(mesh._waitingActions, mesh, scene);
  20728. mesh._waitingActions = undefined;
  20729. }
  20730. }
  20731. // freeze world matrix application
  20732. for (index = 0; index < scene.meshes.length; index++) {
  20733. var currentMesh = scene.meshes[index];
  20734. if (currentMesh._waitingFreezeWorldMatrix) {
  20735. currentMesh.freezeWorldMatrix();
  20736. currentMesh._waitingFreezeWorldMatrix = undefined;
  20737. }
  20738. }
  20739. // Particles Systems
  20740. if (parsedData.particleSystems) {
  20741. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20742. var parsedParticleSystem = parsedData.particleSystems[index];
  20743. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20744. }
  20745. }
  20746. // Lens flares
  20747. if (parsedData.lensFlareSystems) {
  20748. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20749. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20750. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20751. }
  20752. }
  20753. // Shadows
  20754. if (parsedData.shadowGenerators) {
  20755. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20756. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20757. parseShadowGenerator(parsedShadowGenerator, scene);
  20758. }
  20759. }
  20760. // Actions (scene)
  20761. if (parsedData.actions) {
  20762. parseActions(parsedData.actions, null, scene);
  20763. }
  20764. // Finish
  20765. return true;
  20766. }
  20767. });
  20768. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20769. })(BABYLON || (BABYLON = {}));
  20770. var BABYLON;
  20771. (function (BABYLON) {
  20772. var SpriteManager = (function () {
  20773. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20774. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20775. this.name = name;
  20776. this.cellSize = cellSize;
  20777. this.sprites = new Array();
  20778. this.renderingGroupId = 0;
  20779. this.layerMask = 0x0FFFFFFF;
  20780. this.fogEnabled = true;
  20781. this.isPickable = false;
  20782. this._vertexDeclaration = [4, 4, 4, 4];
  20783. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20784. this._capacity = capacity;
  20785. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20786. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20787. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20788. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20789. this._scene = scene;
  20790. this._scene.spriteManagers.push(this);
  20791. // VBO
  20792. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20793. var indices = [];
  20794. var index = 0;
  20795. for (var count = 0; count < capacity; count++) {
  20796. indices.push(index);
  20797. indices.push(index + 1);
  20798. indices.push(index + 2);
  20799. indices.push(index);
  20800. indices.push(index + 2);
  20801. indices.push(index + 3);
  20802. index += 4;
  20803. }
  20804. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20805. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20806. // Effects
  20807. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20808. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20809. }
  20810. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20811. var arrayOffset = index * 16;
  20812. if (offsetX === 0)
  20813. offsetX = this._epsilon;
  20814. else if (offsetX === 1)
  20815. offsetX = 1 - this._epsilon;
  20816. if (offsetY === 0)
  20817. offsetY = this._epsilon;
  20818. else if (offsetY === 1)
  20819. offsetY = 1 - this._epsilon;
  20820. this._vertices[arrayOffset] = sprite.position.x;
  20821. this._vertices[arrayOffset + 1] = sprite.position.y;
  20822. this._vertices[arrayOffset + 2] = sprite.position.z;
  20823. this._vertices[arrayOffset + 3] = sprite.angle;
  20824. this._vertices[arrayOffset + 4] = sprite.width;
  20825. this._vertices[arrayOffset + 5] = sprite.height;
  20826. this._vertices[arrayOffset + 6] = offsetX;
  20827. this._vertices[arrayOffset + 7] = offsetY;
  20828. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20829. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20830. var offset = (sprite.cellIndex / rowSize) >> 0;
  20831. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20832. this._vertices[arrayOffset + 11] = offset;
  20833. // Color
  20834. this._vertices[arrayOffset + 12] = sprite.color.r;
  20835. this._vertices[arrayOffset + 13] = sprite.color.g;
  20836. this._vertices[arrayOffset + 14] = sprite.color.b;
  20837. this._vertices[arrayOffset + 15] = sprite.color.a;
  20838. };
  20839. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20840. var count = Math.min(this._capacity, this.sprites.length);
  20841. var min = BABYLON.Vector3.Zero();
  20842. var max = BABYLON.Vector3.Zero();
  20843. var distance = Number.MAX_VALUE;
  20844. var currentSprite;
  20845. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20846. var cameraView = camera.getViewMatrix();
  20847. for (var index = 0; index < count; index++) {
  20848. var sprite = this.sprites[index];
  20849. if (!sprite) {
  20850. continue;
  20851. }
  20852. if (predicate) {
  20853. if (!predicate(sprite)) {
  20854. continue;
  20855. }
  20856. }
  20857. else if (!sprite.isPickable) {
  20858. continue;
  20859. }
  20860. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20861. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20862. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20863. if (ray.intersectsBoxMinMax(min, max)) {
  20864. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20865. if (distance > currentDistance) {
  20866. distance = currentDistance;
  20867. currentSprite = sprite;
  20868. if (fastCheck) {
  20869. break;
  20870. }
  20871. }
  20872. }
  20873. }
  20874. if (currentSprite) {
  20875. var result = new BABYLON.PickingInfo();
  20876. result.hit = true;
  20877. result.pickedSprite = currentSprite;
  20878. result.distance = distance;
  20879. return result;
  20880. }
  20881. return null;
  20882. };
  20883. SpriteManager.prototype.render = function () {
  20884. // Check
  20885. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20886. return;
  20887. var engine = this._scene.getEngine();
  20888. var baseSize = this._spriteTexture.getBaseSize();
  20889. // Sprites
  20890. var deltaTime = engine.getDeltaTime();
  20891. var max = Math.min(this._capacity, this.sprites.length);
  20892. var rowSize = baseSize.width / this.cellSize;
  20893. var offset = 0;
  20894. for (var index = 0; index < max; index++) {
  20895. var sprite = this.sprites[index];
  20896. if (!sprite) {
  20897. continue;
  20898. }
  20899. sprite._animate(deltaTime);
  20900. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20901. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20902. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20903. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20904. }
  20905. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20906. // Render
  20907. var effect = this._effectBase;
  20908. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20909. effect = this._effectFog;
  20910. }
  20911. engine.enableEffect(effect);
  20912. var viewMatrix = this._scene.getViewMatrix();
  20913. effect.setTexture("diffuseSampler", this._spriteTexture);
  20914. effect.setMatrix("view", viewMatrix);
  20915. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20916. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20917. // Fog
  20918. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20919. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20920. effect.setColor3("vFogColor", this._scene.fogColor);
  20921. }
  20922. // VBOs
  20923. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20924. // Draw order
  20925. engine.setDepthFunctionToLessOrEqual();
  20926. effect.setBool("alphaTest", true);
  20927. engine.setColorWrite(false);
  20928. engine.draw(true, 0, max * 6);
  20929. engine.setColorWrite(true);
  20930. effect.setBool("alphaTest", false);
  20931. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20932. engine.draw(true, 0, max * 6);
  20933. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20934. };
  20935. SpriteManager.prototype.dispose = function () {
  20936. if (this._vertexBuffer) {
  20937. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20938. this._vertexBuffer = null;
  20939. }
  20940. if (this._indexBuffer) {
  20941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20942. this._indexBuffer = null;
  20943. }
  20944. if (this._spriteTexture) {
  20945. this._spriteTexture.dispose();
  20946. this._spriteTexture = null;
  20947. }
  20948. // Remove from scene
  20949. var index = this._scene.spriteManagers.indexOf(this);
  20950. this._scene.spriteManagers.splice(index, 1);
  20951. // Callback
  20952. if (this.onDispose) {
  20953. this.onDispose();
  20954. }
  20955. };
  20956. return SpriteManager;
  20957. })();
  20958. BABYLON.SpriteManager = SpriteManager;
  20959. })(BABYLON || (BABYLON = {}));
  20960. var BABYLON;
  20961. (function (BABYLON) {
  20962. var Sprite = (function () {
  20963. function Sprite(name, manager) {
  20964. this.name = name;
  20965. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20966. this.width = 1.0;
  20967. this.height = 1.0;
  20968. this.angle = 0;
  20969. this.cellIndex = 0;
  20970. this.invertU = 0;
  20971. this.invertV = 0;
  20972. this.animations = new Array();
  20973. this.isPickable = false;
  20974. this._animationStarted = false;
  20975. this._loopAnimation = false;
  20976. this._fromIndex = 0;
  20977. this._toIndex = 0;
  20978. this._delay = 0;
  20979. this._direction = 1;
  20980. this._frameCount = 0;
  20981. this._time = 0;
  20982. this._manager = manager;
  20983. this._manager.sprites.push(this);
  20984. this.position = BABYLON.Vector3.Zero();
  20985. }
  20986. Object.defineProperty(Sprite.prototype, "size", {
  20987. get: function () {
  20988. return this.width;
  20989. },
  20990. set: function (value) {
  20991. this.width = value;
  20992. this.height = value;
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20998. this._fromIndex = from;
  20999. this._toIndex = to;
  21000. this._loopAnimation = loop;
  21001. this._delay = delay;
  21002. this._animationStarted = true;
  21003. this._direction = from < to ? 1 : -1;
  21004. this.cellIndex = from;
  21005. this._time = 0;
  21006. };
  21007. Sprite.prototype.stopAnimation = function () {
  21008. this._animationStarted = false;
  21009. };
  21010. Sprite.prototype._animate = function (deltaTime) {
  21011. if (!this._animationStarted)
  21012. return;
  21013. this._time += deltaTime;
  21014. if (this._time > this._delay) {
  21015. this._time = this._time % this._delay;
  21016. this.cellIndex += this._direction;
  21017. if (this.cellIndex == this._toIndex) {
  21018. if (this._loopAnimation) {
  21019. this.cellIndex = this._fromIndex;
  21020. }
  21021. else {
  21022. this._animationStarted = false;
  21023. if (this.disposeWhenFinishedAnimating) {
  21024. this.dispose();
  21025. }
  21026. }
  21027. }
  21028. }
  21029. };
  21030. Sprite.prototype.dispose = function () {
  21031. for (var i = 0; i < this._manager.sprites.length; i++) {
  21032. if (this._manager.sprites[i] == this) {
  21033. this._manager.sprites.splice(i, 1);
  21034. }
  21035. }
  21036. };
  21037. return Sprite;
  21038. })();
  21039. BABYLON.Sprite = Sprite;
  21040. })(BABYLON || (BABYLON = {}));
  21041. var BABYLON;
  21042. (function (BABYLON) {
  21043. var Layer = (function () {
  21044. function Layer(name, imgUrl, scene, isBackground, color) {
  21045. this.name = name;
  21046. this._vertexDeclaration = [2];
  21047. this._vertexStrideSize = 2 * 4;
  21048. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21049. this.isBackground = isBackground === undefined ? true : isBackground;
  21050. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21051. this._scene = scene;
  21052. this._scene.layers.push(this);
  21053. // VBO
  21054. var vertices = [];
  21055. vertices.push(1, 1);
  21056. vertices.push(-1, 1);
  21057. vertices.push(-1, -1);
  21058. vertices.push(1, -1);
  21059. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21060. // Indices
  21061. var indices = [];
  21062. indices.push(0);
  21063. indices.push(1);
  21064. indices.push(2);
  21065. indices.push(0);
  21066. indices.push(2);
  21067. indices.push(3);
  21068. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21069. // Effects
  21070. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21071. }
  21072. Layer.prototype.render = function () {
  21073. // Check
  21074. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21075. return;
  21076. var engine = this._scene.getEngine();
  21077. // Render
  21078. engine.enableEffect(this._effect);
  21079. engine.setState(false);
  21080. // Texture
  21081. this._effect.setTexture("textureSampler", this.texture);
  21082. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21083. // Color
  21084. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21085. // VBOs
  21086. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21087. // Draw order
  21088. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21089. engine.draw(true, 0, 6);
  21090. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21091. };
  21092. Layer.prototype.dispose = function () {
  21093. if (this._vertexBuffer) {
  21094. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21095. this._vertexBuffer = null;
  21096. }
  21097. if (this._indexBuffer) {
  21098. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21099. this._indexBuffer = null;
  21100. }
  21101. if (this.texture) {
  21102. this.texture.dispose();
  21103. this.texture = null;
  21104. }
  21105. // Remove from scene
  21106. var index = this._scene.layers.indexOf(this);
  21107. this._scene.layers.splice(index, 1);
  21108. // Callback
  21109. if (this.onDispose) {
  21110. this.onDispose();
  21111. }
  21112. };
  21113. return Layer;
  21114. })();
  21115. BABYLON.Layer = Layer;
  21116. })(BABYLON || (BABYLON = {}));
  21117. var BABYLON;
  21118. (function (BABYLON) {
  21119. var Particle = (function () {
  21120. function Particle() {
  21121. this.position = BABYLON.Vector3.Zero();
  21122. this.direction = BABYLON.Vector3.Zero();
  21123. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21124. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21125. this.lifeTime = 1.0;
  21126. this.age = 0;
  21127. this.size = 0;
  21128. this.angle = 0;
  21129. this.angularSpeed = 0;
  21130. }
  21131. Particle.prototype.copyTo = function (other) {
  21132. other.position.copyFrom(this.position);
  21133. other.direction.copyFrom(this.direction);
  21134. other.color.copyFrom(this.color);
  21135. other.colorStep.copyFrom(this.colorStep);
  21136. other.lifeTime = this.lifeTime;
  21137. other.age = this.age;
  21138. other.size = this.size;
  21139. other.angle = this.angle;
  21140. other.angularSpeed = this.angularSpeed;
  21141. };
  21142. return Particle;
  21143. })();
  21144. BABYLON.Particle = Particle;
  21145. })(BABYLON || (BABYLON = {}));
  21146. var BABYLON;
  21147. (function (BABYLON) {
  21148. var randomNumber = function (min, max) {
  21149. if (min === max) {
  21150. return (min);
  21151. }
  21152. var random = Math.random();
  21153. return ((random * (max - min)) + min);
  21154. };
  21155. var ParticleSystem = (function () {
  21156. function ParticleSystem(name, capacity, scene, customEffect) {
  21157. var _this = this;
  21158. this.name = name;
  21159. this.renderingGroupId = 0;
  21160. this.emitter = null;
  21161. this.emitRate = 10;
  21162. this.manualEmitCount = -1;
  21163. this.updateSpeed = 0.01;
  21164. this.targetStopDuration = 0;
  21165. this.disposeOnStop = false;
  21166. this.minEmitPower = 1;
  21167. this.maxEmitPower = 1;
  21168. this.minLifeTime = 1;
  21169. this.maxLifeTime = 1;
  21170. this.minSize = 1;
  21171. this.maxSize = 1;
  21172. this.minAngularSpeed = 0;
  21173. this.maxAngularSpeed = 0;
  21174. this.layerMask = 0x0FFFFFFF;
  21175. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21176. this.forceDepthWrite = false;
  21177. this.gravity = BABYLON.Vector3.Zero();
  21178. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21179. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21180. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21181. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21182. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21183. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21184. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21185. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21186. this.particles = new Array();
  21187. this._vertexDeclaration = [3, 4, 4];
  21188. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21189. this._stockParticles = new Array();
  21190. this._newPartsExcess = 0;
  21191. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21192. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21193. this._scaledDirection = BABYLON.Vector3.Zero();
  21194. this._scaledGravity = BABYLON.Vector3.Zero();
  21195. this._currentRenderId = -1;
  21196. this._started = false;
  21197. this._stopped = false;
  21198. this._actualFrame = 0;
  21199. this.id = name;
  21200. this._capacity = capacity;
  21201. this._scene = scene;
  21202. this._customEffect = customEffect;
  21203. scene.particleSystems.push(this);
  21204. // VBO
  21205. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21206. var indices = [];
  21207. var index = 0;
  21208. for (var count = 0; count < capacity; count++) {
  21209. indices.push(index);
  21210. indices.push(index + 1);
  21211. indices.push(index + 2);
  21212. indices.push(index);
  21213. indices.push(index + 2);
  21214. indices.push(index + 3);
  21215. index += 4;
  21216. }
  21217. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21218. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21219. // Default behaviors
  21220. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21221. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21222. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21223. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21224. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21225. };
  21226. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21227. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21228. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21229. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21231. };
  21232. this.updateFunction = function (particles) {
  21233. for (var index = 0; index < particles.length; index++) {
  21234. var particle = particles[index];
  21235. particle.age += _this._scaledUpdateSpeed;
  21236. if (particle.age >= particle.lifeTime) {
  21237. _this.recycleParticle(particle);
  21238. index--;
  21239. continue;
  21240. }
  21241. else {
  21242. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21243. particle.color.addInPlace(_this._scaledColorStep);
  21244. if (particle.color.a < 0)
  21245. particle.color.a = 0;
  21246. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21247. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21248. particle.position.addInPlace(_this._scaledDirection);
  21249. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21250. particle.direction.addInPlace(_this._scaledGravity);
  21251. }
  21252. }
  21253. };
  21254. }
  21255. ParticleSystem.prototype.recycleParticle = function (particle) {
  21256. var lastParticle = this.particles.pop();
  21257. if (lastParticle !== particle) {
  21258. lastParticle.copyTo(particle);
  21259. this._stockParticles.push(lastParticle);
  21260. }
  21261. };
  21262. ParticleSystem.prototype.getCapacity = function () {
  21263. return this._capacity;
  21264. };
  21265. ParticleSystem.prototype.isAlive = function () {
  21266. return this._alive;
  21267. };
  21268. ParticleSystem.prototype.isStarted = function () {
  21269. return this._started;
  21270. };
  21271. ParticleSystem.prototype.start = function () {
  21272. this._started = true;
  21273. this._stopped = false;
  21274. this._actualFrame = 0;
  21275. };
  21276. ParticleSystem.prototype.stop = function () {
  21277. this._stopped = true;
  21278. };
  21279. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21280. var offset = index * 11;
  21281. this._vertices[offset] = particle.position.x;
  21282. this._vertices[offset + 1] = particle.position.y;
  21283. this._vertices[offset + 2] = particle.position.z;
  21284. this._vertices[offset + 3] = particle.color.r;
  21285. this._vertices[offset + 4] = particle.color.g;
  21286. this._vertices[offset + 5] = particle.color.b;
  21287. this._vertices[offset + 6] = particle.color.a;
  21288. this._vertices[offset + 7] = particle.angle;
  21289. this._vertices[offset + 8] = particle.size;
  21290. this._vertices[offset + 9] = offsetX;
  21291. this._vertices[offset + 10] = offsetY;
  21292. };
  21293. ParticleSystem.prototype._update = function (newParticles) {
  21294. // Update current
  21295. this._alive = this.particles.length > 0;
  21296. this.updateFunction(this.particles);
  21297. // Add new ones
  21298. var worldMatrix;
  21299. if (this.emitter.position) {
  21300. worldMatrix = this.emitter.getWorldMatrix();
  21301. }
  21302. else {
  21303. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21304. }
  21305. for (var index = 0; index < newParticles; index++) {
  21306. if (this.particles.length === this._capacity) {
  21307. break;
  21308. }
  21309. if (this._stockParticles.length !== 0) {
  21310. var particle = this._stockParticles.pop();
  21311. particle.age = 0;
  21312. }
  21313. else {
  21314. particle = new BABYLON.Particle();
  21315. }
  21316. this.particles.push(particle);
  21317. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21318. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21319. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21320. particle.size = randomNumber(this.minSize, this.maxSize);
  21321. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21322. this.startPositionFunction(worldMatrix, particle.position);
  21323. var step = randomNumber(0, 1.0);
  21324. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21325. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21326. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21327. }
  21328. };
  21329. ParticleSystem.prototype._getEffect = function () {
  21330. if (this._customEffect) {
  21331. return this._customEffect;
  21332. }
  21333. ;
  21334. var defines = [];
  21335. if (this._scene.clipPlane) {
  21336. defines.push("#define CLIPPLANE");
  21337. }
  21338. // Effect
  21339. var join = defines.join("\n");
  21340. if (this._cachedDefines !== join) {
  21341. this._cachedDefines = join;
  21342. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21343. }
  21344. return this._effect;
  21345. };
  21346. ParticleSystem.prototype.animate = function () {
  21347. if (!this._started)
  21348. return;
  21349. var effect = this._getEffect();
  21350. // Check
  21351. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21352. return;
  21353. if (this._currentRenderId === this._scene.getRenderId()) {
  21354. return;
  21355. }
  21356. this._currentRenderId = this._scene.getRenderId();
  21357. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21358. // determine the number of particles we need to create
  21359. var emitCout;
  21360. if (this.manualEmitCount > -1) {
  21361. emitCout = this.manualEmitCount;
  21362. this.manualEmitCount = 0;
  21363. }
  21364. else {
  21365. emitCout = this.emitRate;
  21366. }
  21367. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21368. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21369. if (this._newPartsExcess > 1.0) {
  21370. newParticles += this._newPartsExcess >> 0;
  21371. this._newPartsExcess -= this._newPartsExcess >> 0;
  21372. }
  21373. this._alive = false;
  21374. if (!this._stopped) {
  21375. this._actualFrame += this._scaledUpdateSpeed;
  21376. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21377. this.stop();
  21378. }
  21379. else {
  21380. newParticles = 0;
  21381. }
  21382. this._update(newParticles);
  21383. // Stopped?
  21384. if (this._stopped) {
  21385. if (!this._alive) {
  21386. this._started = false;
  21387. if (this.disposeOnStop) {
  21388. this._scene._toBeDisposed.push(this);
  21389. }
  21390. }
  21391. }
  21392. // Update VBO
  21393. var offset = 0;
  21394. for (var index = 0; index < this.particles.length; index++) {
  21395. var particle = this.particles[index];
  21396. this._appendParticleVertex(offset++, particle, 0, 0);
  21397. this._appendParticleVertex(offset++, particle, 1, 0);
  21398. this._appendParticleVertex(offset++, particle, 1, 1);
  21399. this._appendParticleVertex(offset++, particle, 0, 1);
  21400. }
  21401. var engine = this._scene.getEngine();
  21402. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21403. };
  21404. ParticleSystem.prototype.render = function () {
  21405. var effect = this._getEffect();
  21406. // Check
  21407. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21408. return 0;
  21409. var engine = this._scene.getEngine();
  21410. // Render
  21411. engine.enableEffect(effect);
  21412. engine.setState(false);
  21413. var viewMatrix = this._scene.getViewMatrix();
  21414. effect.setTexture("diffuseSampler", this.particleTexture);
  21415. effect.setMatrix("view", viewMatrix);
  21416. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21417. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21418. if (this._scene.clipPlane) {
  21419. var clipPlane = this._scene.clipPlane;
  21420. var invView = viewMatrix.clone();
  21421. invView.invert();
  21422. effect.setMatrix("invView", invView);
  21423. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21424. }
  21425. // VBOs
  21426. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21427. // Draw order
  21428. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21429. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21430. }
  21431. else {
  21432. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21433. }
  21434. if (this.forceDepthWrite) {
  21435. engine.setDepthWrite(true);
  21436. }
  21437. engine.draw(true, 0, this.particles.length * 6);
  21438. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21439. return this.particles.length;
  21440. };
  21441. ParticleSystem.prototype.dispose = function () {
  21442. if (this._vertexBuffer) {
  21443. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21444. this._vertexBuffer = null;
  21445. }
  21446. if (this._indexBuffer) {
  21447. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21448. this._indexBuffer = null;
  21449. }
  21450. if (this.particleTexture) {
  21451. this.particleTexture.dispose();
  21452. this.particleTexture = null;
  21453. }
  21454. // Remove from scene
  21455. var index = this._scene.particleSystems.indexOf(this);
  21456. this._scene.particleSystems.splice(index, 1);
  21457. // Callback
  21458. if (this.onDispose) {
  21459. this.onDispose();
  21460. }
  21461. };
  21462. // Clone
  21463. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21464. var result = new ParticleSystem(name, this._capacity, this._scene);
  21465. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21466. if (newEmitter === undefined) {
  21467. newEmitter = this.emitter;
  21468. }
  21469. result.emitter = newEmitter;
  21470. if (this.particleTexture) {
  21471. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21472. }
  21473. result.start();
  21474. return result;
  21475. };
  21476. // Statics
  21477. ParticleSystem.BLENDMODE_ONEONE = 0;
  21478. ParticleSystem.BLENDMODE_STANDARD = 1;
  21479. return ParticleSystem;
  21480. })();
  21481. BABYLON.ParticleSystem = ParticleSystem;
  21482. })(BABYLON || (BABYLON = {}));
  21483. var BABYLON;
  21484. (function (BABYLON) {
  21485. var AnimationRange = (function () {
  21486. function AnimationRange(name, from, to) {
  21487. this.name = name;
  21488. this.from = from;
  21489. this.to = to;
  21490. }
  21491. return AnimationRange;
  21492. })();
  21493. BABYLON.AnimationRange = AnimationRange;
  21494. var Animation = (function () {
  21495. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21496. this.name = name;
  21497. this.targetProperty = targetProperty;
  21498. this.framePerSecond = framePerSecond;
  21499. this.dataType = dataType;
  21500. this.loopMode = loopMode;
  21501. this._offsetsCache = {};
  21502. this._highLimitsCache = {};
  21503. this._stopped = false;
  21504. this.allowMatricesInterpolation = false;
  21505. this._ranges = new Array();
  21506. this.targetPropertyPath = targetProperty.split(".");
  21507. this.dataType = dataType;
  21508. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21509. }
  21510. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21511. var dataType = undefined;
  21512. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21513. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21514. }
  21515. else if (from instanceof BABYLON.Quaternion) {
  21516. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21517. }
  21518. else if (from instanceof BABYLON.Vector3) {
  21519. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21520. }
  21521. else if (from instanceof BABYLON.Vector2) {
  21522. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21523. }
  21524. else if (from instanceof BABYLON.Color3) {
  21525. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21526. }
  21527. if (dataType == undefined) {
  21528. return null;
  21529. }
  21530. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21531. var keys = [];
  21532. keys.push({ frame: 0, value: from });
  21533. keys.push({ frame: totalFrame, value: to });
  21534. animation.setKeys(keys);
  21535. if (easingFunction !== undefined) {
  21536. animation.setEasingFunction(easingFunction);
  21537. }
  21538. mesh.animations.push(animation);
  21539. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21540. };
  21541. // Methods
  21542. Animation.prototype.createRange = function (name, from, to) {
  21543. this._ranges.push(new AnimationRange(name, from, to));
  21544. };
  21545. Animation.prototype.deleteRange = function (name) {
  21546. for (var index = 0; index < this._ranges.length; index++) {
  21547. if (this._ranges[index].name === name) {
  21548. this._ranges.splice(index, 1);
  21549. return;
  21550. }
  21551. }
  21552. };
  21553. Animation.prototype.getRange = function (name) {
  21554. for (var index = 0; index < this._ranges.length; index++) {
  21555. if (this._ranges[index].name === name) {
  21556. return this._ranges[index];
  21557. }
  21558. }
  21559. return null;
  21560. };
  21561. Animation.prototype.reset = function () {
  21562. this._offsetsCache = {};
  21563. this._highLimitsCache = {};
  21564. this.currentFrame = 0;
  21565. };
  21566. Animation.prototype.isStopped = function () {
  21567. return this._stopped;
  21568. };
  21569. Animation.prototype.getKeys = function () {
  21570. return this._keys;
  21571. };
  21572. Animation.prototype.getEasingFunction = function () {
  21573. return this._easingFunction;
  21574. };
  21575. Animation.prototype.setEasingFunction = function (easingFunction) {
  21576. this._easingFunction = easingFunction;
  21577. };
  21578. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21579. return startValue + (endValue - startValue) * gradient;
  21580. };
  21581. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21582. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21583. };
  21584. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21585. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21586. };
  21587. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21588. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21589. };
  21590. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21591. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21592. };
  21593. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21594. var startScale = new BABYLON.Vector3(0, 0, 0);
  21595. var startRotation = new BABYLON.Quaternion();
  21596. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21597. startValue.decompose(startScale, startRotation, startTranslation);
  21598. var endScale = new BABYLON.Vector3(0, 0, 0);
  21599. var endRotation = new BABYLON.Quaternion();
  21600. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21601. endValue.decompose(endScale, endRotation, endTranslation);
  21602. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21603. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21604. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21605. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21606. return result;
  21607. };
  21608. Animation.prototype.clone = function () {
  21609. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21610. if (this._keys) {
  21611. clone.setKeys(this._keys);
  21612. }
  21613. return clone;
  21614. };
  21615. Animation.prototype.setKeys = function (values) {
  21616. this._keys = values.slice(0);
  21617. this._offsetsCache = {};
  21618. this._highLimitsCache = {};
  21619. };
  21620. Animation.prototype._getKeyValue = function (value) {
  21621. if (typeof value === "function") {
  21622. return value();
  21623. }
  21624. return value;
  21625. };
  21626. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21627. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21628. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21629. }
  21630. this.currentFrame = currentFrame;
  21631. // Try to get a hash to find the right key
  21632. 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));
  21633. if (this._keys[startKey].frame >= currentFrame) {
  21634. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21635. startKey--;
  21636. }
  21637. }
  21638. for (var key = startKey; key < this._keys.length; key++) {
  21639. if (this._keys[key + 1].frame >= currentFrame) {
  21640. var startValue = this._getKeyValue(this._keys[key].value);
  21641. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21642. // gradient : percent of currentFrame between the frame inf and the frame sup
  21643. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21644. // check for easingFunction and correction of gradient
  21645. if (this._easingFunction != null) {
  21646. gradient = this._easingFunction.ease(gradient);
  21647. }
  21648. switch (this.dataType) {
  21649. // Float
  21650. case Animation.ANIMATIONTYPE_FLOAT:
  21651. switch (loopMode) {
  21652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21654. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21656. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21657. }
  21658. break;
  21659. // Quaternion
  21660. case Animation.ANIMATIONTYPE_QUATERNION:
  21661. var quaternion = null;
  21662. switch (loopMode) {
  21663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21665. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21666. break;
  21667. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21668. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21669. break;
  21670. }
  21671. return quaternion;
  21672. // Vector3
  21673. case Animation.ANIMATIONTYPE_VECTOR3:
  21674. switch (loopMode) {
  21675. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21676. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21677. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21678. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21679. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21680. }
  21681. // Vector2
  21682. case Animation.ANIMATIONTYPE_VECTOR2:
  21683. switch (loopMode) {
  21684. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21685. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21686. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21687. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21688. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21689. }
  21690. // Color3
  21691. case Animation.ANIMATIONTYPE_COLOR3:
  21692. switch (loopMode) {
  21693. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21694. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21695. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21696. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21697. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21698. }
  21699. // Matrix
  21700. case Animation.ANIMATIONTYPE_MATRIX:
  21701. switch (loopMode) {
  21702. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21703. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21704. if (this.allowMatricesInterpolation) {
  21705. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21706. }
  21707. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21708. return startValue;
  21709. }
  21710. default:
  21711. break;
  21712. }
  21713. break;
  21714. }
  21715. }
  21716. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21717. };
  21718. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21719. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21720. this._stopped = true;
  21721. return false;
  21722. }
  21723. var returnValue = true;
  21724. // Adding a start key at frame 0 if missing
  21725. if (this._keys[0].frame !== 0) {
  21726. var newKey = { frame: 0, value: this._keys[0].value };
  21727. this._keys.splice(0, 0, newKey);
  21728. }
  21729. // Check limits
  21730. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21731. from = this._keys[0].frame;
  21732. }
  21733. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21734. to = this._keys[this._keys.length - 1].frame;
  21735. }
  21736. // Compute ratio
  21737. var range = to - from;
  21738. var offsetValue;
  21739. // ratio represents the frame delta between from and to
  21740. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21741. var highLimitValue = 0;
  21742. if (ratio > range && !loop) {
  21743. returnValue = false;
  21744. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21745. }
  21746. else {
  21747. // Get max value if required
  21748. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21749. var keyOffset = to.toString() + from.toString();
  21750. if (!this._offsetsCache[keyOffset]) {
  21751. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21752. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21753. switch (this.dataType) {
  21754. // Float
  21755. case Animation.ANIMATIONTYPE_FLOAT:
  21756. this._offsetsCache[keyOffset] = toValue - fromValue;
  21757. break;
  21758. // Quaternion
  21759. case Animation.ANIMATIONTYPE_QUATERNION:
  21760. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21761. break;
  21762. // Vector3
  21763. case Animation.ANIMATIONTYPE_VECTOR3:
  21764. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21765. // Vector2
  21766. case Animation.ANIMATIONTYPE_VECTOR2:
  21767. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21768. // Color3
  21769. case Animation.ANIMATIONTYPE_COLOR3:
  21770. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21771. default:
  21772. break;
  21773. }
  21774. this._highLimitsCache[keyOffset] = toValue;
  21775. }
  21776. highLimitValue = this._highLimitsCache[keyOffset];
  21777. offsetValue = this._offsetsCache[keyOffset];
  21778. }
  21779. }
  21780. if (offsetValue === undefined) {
  21781. switch (this.dataType) {
  21782. // Float
  21783. case Animation.ANIMATIONTYPE_FLOAT:
  21784. offsetValue = 0;
  21785. break;
  21786. // Quaternion
  21787. case Animation.ANIMATIONTYPE_QUATERNION:
  21788. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21789. break;
  21790. // Vector3
  21791. case Animation.ANIMATIONTYPE_VECTOR3:
  21792. offsetValue = BABYLON.Vector3.Zero();
  21793. break;
  21794. // Vector2
  21795. case Animation.ANIMATIONTYPE_VECTOR2:
  21796. offsetValue = BABYLON.Vector2.Zero();
  21797. break;
  21798. // Color3
  21799. case Animation.ANIMATIONTYPE_COLOR3:
  21800. offsetValue = BABYLON.Color3.Black();
  21801. }
  21802. }
  21803. // Compute value
  21804. var repeatCount = (ratio / range) >> 0;
  21805. var currentFrame = returnValue ? from + ratio % range : to;
  21806. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21807. // Set value
  21808. if (this.targetPropertyPath.length > 1) {
  21809. var property = this._target[this.targetPropertyPath[0]];
  21810. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21811. property = property[this.targetPropertyPath[index]];
  21812. }
  21813. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21814. }
  21815. else {
  21816. this._target[this.targetPropertyPath[0]] = currentValue;
  21817. }
  21818. if (this._target.markAsDirty) {
  21819. this._target.markAsDirty(this.targetProperty);
  21820. }
  21821. if (!returnValue) {
  21822. this._stopped = true;
  21823. }
  21824. return returnValue;
  21825. };
  21826. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21827. get: function () {
  21828. return Animation._ANIMATIONTYPE_FLOAT;
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21834. get: function () {
  21835. return Animation._ANIMATIONTYPE_VECTOR3;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21841. get: function () {
  21842. return Animation._ANIMATIONTYPE_VECTOR2;
  21843. },
  21844. enumerable: true,
  21845. configurable: true
  21846. });
  21847. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21848. get: function () {
  21849. return Animation._ANIMATIONTYPE_QUATERNION;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21855. get: function () {
  21856. return Animation._ANIMATIONTYPE_MATRIX;
  21857. },
  21858. enumerable: true,
  21859. configurable: true
  21860. });
  21861. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21862. get: function () {
  21863. return Animation._ANIMATIONTYPE_COLOR3;
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21869. get: function () {
  21870. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21876. get: function () {
  21877. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21883. get: function () {
  21884. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. // Statics
  21890. Animation._ANIMATIONTYPE_FLOAT = 0;
  21891. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21892. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21893. Animation._ANIMATIONTYPE_MATRIX = 3;
  21894. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21895. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21896. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21897. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21898. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21899. return Animation;
  21900. })();
  21901. BABYLON.Animation = Animation;
  21902. })(BABYLON || (BABYLON = {}));
  21903. var BABYLON;
  21904. (function (BABYLON) {
  21905. var Animatable = (function () {
  21906. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21907. if (fromFrame === void 0) { fromFrame = 0; }
  21908. if (toFrame === void 0) { toFrame = 100; }
  21909. if (loopAnimation === void 0) { loopAnimation = false; }
  21910. if (speedRatio === void 0) { speedRatio = 1.0; }
  21911. this.target = target;
  21912. this.fromFrame = fromFrame;
  21913. this.toFrame = toFrame;
  21914. this.loopAnimation = loopAnimation;
  21915. this.speedRatio = speedRatio;
  21916. this.onAnimationEnd = onAnimationEnd;
  21917. this._animations = new Array();
  21918. this._paused = false;
  21919. this.animationStarted = false;
  21920. if (animations) {
  21921. this.appendAnimations(target, animations);
  21922. }
  21923. this._scene = scene;
  21924. scene._activeAnimatables.push(this);
  21925. }
  21926. // Methods
  21927. Animatable.prototype.getAnimations = function () {
  21928. return this._animations;
  21929. };
  21930. Animatable.prototype.appendAnimations = function (target, animations) {
  21931. for (var index = 0; index < animations.length; index++) {
  21932. var animation = animations[index];
  21933. animation._target = target;
  21934. this._animations.push(animation);
  21935. }
  21936. };
  21937. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21938. var animations = this._animations;
  21939. for (var index = 0; index < animations.length; index++) {
  21940. if (animations[index].targetProperty === property) {
  21941. return animations[index];
  21942. }
  21943. }
  21944. return null;
  21945. };
  21946. Animatable.prototype.reset = function () {
  21947. var animations = this._animations;
  21948. for (var index = 0; index < animations.length; index++) {
  21949. animations[index].reset();
  21950. }
  21951. this._localDelayOffset = null;
  21952. this._pausedDelay = null;
  21953. };
  21954. Animatable.prototype.pause = function () {
  21955. if (this._paused) {
  21956. return;
  21957. }
  21958. this._paused = true;
  21959. };
  21960. Animatable.prototype.restart = function () {
  21961. this._paused = false;
  21962. };
  21963. Animatable.prototype.stop = function () {
  21964. var index = this._scene._activeAnimatables.indexOf(this);
  21965. if (index > -1) {
  21966. this._scene._activeAnimatables.splice(index, 1);
  21967. }
  21968. if (this.onAnimationEnd) {
  21969. this.onAnimationEnd();
  21970. }
  21971. };
  21972. Animatable.prototype._animate = function (delay) {
  21973. if (this._paused) {
  21974. if (!this._pausedDelay) {
  21975. this._pausedDelay = delay;
  21976. }
  21977. return true;
  21978. }
  21979. if (!this._localDelayOffset) {
  21980. this._localDelayOffset = delay;
  21981. }
  21982. else if (this._pausedDelay) {
  21983. this._localDelayOffset += delay - this._pausedDelay;
  21984. this._pausedDelay = null;
  21985. }
  21986. // Animating
  21987. var running = false;
  21988. var animations = this._animations;
  21989. for (var index = 0; index < animations.length; index++) {
  21990. var animation = animations[index];
  21991. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21992. running = running || isRunning;
  21993. }
  21994. if (!running) {
  21995. // Remove from active animatables
  21996. index = this._scene._activeAnimatables.indexOf(this);
  21997. this._scene._activeAnimatables.splice(index, 1);
  21998. }
  21999. if (!running && this.onAnimationEnd) {
  22000. this.onAnimationEnd();
  22001. }
  22002. return running;
  22003. };
  22004. return Animatable;
  22005. })();
  22006. BABYLON.Animatable = Animatable;
  22007. })(BABYLON || (BABYLON = {}));
  22008. var BABYLON;
  22009. (function (BABYLON) {
  22010. var EasingFunction = (function () {
  22011. function EasingFunction() {
  22012. // Properties
  22013. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22014. }
  22015. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22016. get: function () {
  22017. return EasingFunction._EASINGMODE_EASEIN;
  22018. },
  22019. enumerable: true,
  22020. configurable: true
  22021. });
  22022. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22023. get: function () {
  22024. return EasingFunction._EASINGMODE_EASEOUT;
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22030. get: function () {
  22031. return EasingFunction._EASINGMODE_EASEINOUT;
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22037. var n = Math.min(Math.max(easingMode, 0), 2);
  22038. this._easingMode = n;
  22039. };
  22040. EasingFunction.prototype.getEasingMode = function () {
  22041. return this._easingMode;
  22042. };
  22043. EasingFunction.prototype.easeInCore = function (gradient) {
  22044. throw new Error('You must implement this method');
  22045. };
  22046. EasingFunction.prototype.ease = function (gradient) {
  22047. switch (this._easingMode) {
  22048. case EasingFunction.EASINGMODE_EASEIN:
  22049. return this.easeInCore(gradient);
  22050. case EasingFunction.EASINGMODE_EASEOUT:
  22051. return (1 - this.easeInCore(1 - gradient));
  22052. }
  22053. if (gradient >= 0.5) {
  22054. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22055. }
  22056. return (this.easeInCore(gradient * 2) * 0.5);
  22057. };
  22058. //Statics
  22059. EasingFunction._EASINGMODE_EASEIN = 0;
  22060. EasingFunction._EASINGMODE_EASEOUT = 1;
  22061. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22062. return EasingFunction;
  22063. })();
  22064. BABYLON.EasingFunction = EasingFunction;
  22065. var CircleEase = (function (_super) {
  22066. __extends(CircleEase, _super);
  22067. function CircleEase() {
  22068. _super.apply(this, arguments);
  22069. }
  22070. CircleEase.prototype.easeInCore = function (gradient) {
  22071. gradient = Math.max(0, Math.min(1, gradient));
  22072. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22073. };
  22074. return CircleEase;
  22075. })(EasingFunction);
  22076. BABYLON.CircleEase = CircleEase;
  22077. var BackEase = (function (_super) {
  22078. __extends(BackEase, _super);
  22079. function BackEase(amplitude) {
  22080. if (amplitude === void 0) { amplitude = 1; }
  22081. _super.call(this);
  22082. this.amplitude = amplitude;
  22083. }
  22084. BackEase.prototype.easeInCore = function (gradient) {
  22085. var num = Math.max(0, this.amplitude);
  22086. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22087. };
  22088. return BackEase;
  22089. })(EasingFunction);
  22090. BABYLON.BackEase = BackEase;
  22091. var BounceEase = (function (_super) {
  22092. __extends(BounceEase, _super);
  22093. function BounceEase(bounces, bounciness) {
  22094. if (bounces === void 0) { bounces = 3; }
  22095. if (bounciness === void 0) { bounciness = 2; }
  22096. _super.call(this);
  22097. this.bounces = bounces;
  22098. this.bounciness = bounciness;
  22099. }
  22100. BounceEase.prototype.easeInCore = function (gradient) {
  22101. var y = Math.max(0.0, this.bounces);
  22102. var bounciness = this.bounciness;
  22103. if (bounciness <= 1.0) {
  22104. bounciness = 1.001;
  22105. }
  22106. var num9 = Math.pow(bounciness, y);
  22107. var num5 = 1.0 - bounciness;
  22108. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22109. var num15 = gradient * num4;
  22110. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22111. var num3 = Math.floor(num65);
  22112. var num13 = num3 + 1.0;
  22113. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22114. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22115. var num7 = (num8 + num12) * 0.5;
  22116. var num6 = gradient - num7;
  22117. var num2 = num7 - num8;
  22118. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22119. };
  22120. return BounceEase;
  22121. })(EasingFunction);
  22122. BABYLON.BounceEase = BounceEase;
  22123. var CubicEase = (function (_super) {
  22124. __extends(CubicEase, _super);
  22125. function CubicEase() {
  22126. _super.apply(this, arguments);
  22127. }
  22128. CubicEase.prototype.easeInCore = function (gradient) {
  22129. return (gradient * gradient * gradient);
  22130. };
  22131. return CubicEase;
  22132. })(EasingFunction);
  22133. BABYLON.CubicEase = CubicEase;
  22134. var ElasticEase = (function (_super) {
  22135. __extends(ElasticEase, _super);
  22136. function ElasticEase(oscillations, springiness) {
  22137. if (oscillations === void 0) { oscillations = 3; }
  22138. if (springiness === void 0) { springiness = 3; }
  22139. _super.call(this);
  22140. this.oscillations = oscillations;
  22141. this.springiness = springiness;
  22142. }
  22143. ElasticEase.prototype.easeInCore = function (gradient) {
  22144. var num2;
  22145. var num3 = Math.max(0.0, this.oscillations);
  22146. var num = Math.max(0.0, this.springiness);
  22147. if (num == 0) {
  22148. num2 = gradient;
  22149. }
  22150. else {
  22151. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22152. }
  22153. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22154. };
  22155. return ElasticEase;
  22156. })(EasingFunction);
  22157. BABYLON.ElasticEase = ElasticEase;
  22158. var ExponentialEase = (function (_super) {
  22159. __extends(ExponentialEase, _super);
  22160. function ExponentialEase(exponent) {
  22161. if (exponent === void 0) { exponent = 2; }
  22162. _super.call(this);
  22163. this.exponent = exponent;
  22164. }
  22165. ExponentialEase.prototype.easeInCore = function (gradient) {
  22166. if (this.exponent <= 0) {
  22167. return gradient;
  22168. }
  22169. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22170. };
  22171. return ExponentialEase;
  22172. })(EasingFunction);
  22173. BABYLON.ExponentialEase = ExponentialEase;
  22174. var PowerEase = (function (_super) {
  22175. __extends(PowerEase, _super);
  22176. function PowerEase(power) {
  22177. if (power === void 0) { power = 2; }
  22178. _super.call(this);
  22179. this.power = power;
  22180. }
  22181. PowerEase.prototype.easeInCore = function (gradient) {
  22182. var y = Math.max(0.0, this.power);
  22183. return Math.pow(gradient, y);
  22184. };
  22185. return PowerEase;
  22186. })(EasingFunction);
  22187. BABYLON.PowerEase = PowerEase;
  22188. var QuadraticEase = (function (_super) {
  22189. __extends(QuadraticEase, _super);
  22190. function QuadraticEase() {
  22191. _super.apply(this, arguments);
  22192. }
  22193. QuadraticEase.prototype.easeInCore = function (gradient) {
  22194. return (gradient * gradient);
  22195. };
  22196. return QuadraticEase;
  22197. })(EasingFunction);
  22198. BABYLON.QuadraticEase = QuadraticEase;
  22199. var QuarticEase = (function (_super) {
  22200. __extends(QuarticEase, _super);
  22201. function QuarticEase() {
  22202. _super.apply(this, arguments);
  22203. }
  22204. QuarticEase.prototype.easeInCore = function (gradient) {
  22205. return (gradient * gradient * gradient * gradient);
  22206. };
  22207. return QuarticEase;
  22208. })(EasingFunction);
  22209. BABYLON.QuarticEase = QuarticEase;
  22210. var QuinticEase = (function (_super) {
  22211. __extends(QuinticEase, _super);
  22212. function QuinticEase() {
  22213. _super.apply(this, arguments);
  22214. }
  22215. QuinticEase.prototype.easeInCore = function (gradient) {
  22216. return (gradient * gradient * gradient * gradient * gradient);
  22217. };
  22218. return QuinticEase;
  22219. })(EasingFunction);
  22220. BABYLON.QuinticEase = QuinticEase;
  22221. var SineEase = (function (_super) {
  22222. __extends(SineEase, _super);
  22223. function SineEase() {
  22224. _super.apply(this, arguments);
  22225. }
  22226. SineEase.prototype.easeInCore = function (gradient) {
  22227. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22228. };
  22229. return SineEase;
  22230. })(EasingFunction);
  22231. BABYLON.SineEase = SineEase;
  22232. var BezierCurveEase = (function (_super) {
  22233. __extends(BezierCurveEase, _super);
  22234. function BezierCurveEase(x1, y1, x2, y2) {
  22235. if (x1 === void 0) { x1 = 0; }
  22236. if (y1 === void 0) { y1 = 0; }
  22237. if (x2 === void 0) { x2 = 1; }
  22238. if (y2 === void 0) { y2 = 1; }
  22239. _super.call(this);
  22240. this.x1 = x1;
  22241. this.y1 = y1;
  22242. this.x2 = x2;
  22243. this.y2 = y2;
  22244. }
  22245. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22246. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22247. };
  22248. return BezierCurveEase;
  22249. })(EasingFunction);
  22250. BABYLON.BezierCurveEase = BezierCurveEase;
  22251. })(BABYLON || (BABYLON = {}));
  22252. var BABYLON;
  22253. (function (BABYLON) {
  22254. var Bone = (function (_super) {
  22255. __extends(Bone, _super);
  22256. function Bone(name, skeleton, parentBone, matrix) {
  22257. _super.call(this, name, skeleton.getScene());
  22258. this.name = name;
  22259. this.children = new Array();
  22260. this.animations = new Array();
  22261. this._worldTransform = new BABYLON.Matrix();
  22262. this._absoluteTransform = new BABYLON.Matrix();
  22263. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22264. this._skeleton = skeleton;
  22265. this._matrix = matrix;
  22266. this._baseMatrix = matrix;
  22267. skeleton.bones.push(this);
  22268. if (parentBone) {
  22269. this._parent = parentBone;
  22270. parentBone.children.push(this);
  22271. }
  22272. else {
  22273. this._parent = null;
  22274. }
  22275. this._updateDifferenceMatrix();
  22276. }
  22277. // Members
  22278. Bone.prototype.getParent = function () {
  22279. return this._parent;
  22280. };
  22281. Bone.prototype.getLocalMatrix = function () {
  22282. return this._matrix;
  22283. };
  22284. Bone.prototype.getBaseMatrix = function () {
  22285. return this._baseMatrix;
  22286. };
  22287. Bone.prototype.getWorldMatrix = function () {
  22288. return this._worldTransform;
  22289. };
  22290. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22291. return this._invertedAbsoluteTransform;
  22292. };
  22293. Bone.prototype.getAbsoluteMatrix = function () {
  22294. var matrix = this._matrix.clone();
  22295. var parent = this._parent;
  22296. while (parent) {
  22297. matrix = matrix.multiply(parent.getLocalMatrix());
  22298. parent = parent.getParent();
  22299. }
  22300. return matrix;
  22301. };
  22302. // Methods
  22303. Bone.prototype.updateMatrix = function (matrix) {
  22304. this._matrix = matrix;
  22305. this._skeleton._markAsDirty();
  22306. this._updateDifferenceMatrix();
  22307. };
  22308. Bone.prototype._updateDifferenceMatrix = function () {
  22309. if (this._parent) {
  22310. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22311. }
  22312. else {
  22313. this._absoluteTransform.copyFrom(this._matrix);
  22314. }
  22315. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22316. for (var index = 0; index < this.children.length; index++) {
  22317. this.children[index]._updateDifferenceMatrix();
  22318. }
  22319. };
  22320. Bone.prototype.markAsDirty = function () {
  22321. this._currentRenderId++;
  22322. this._skeleton._markAsDirty();
  22323. };
  22324. return Bone;
  22325. })(BABYLON.Node);
  22326. BABYLON.Bone = Bone;
  22327. })(BABYLON || (BABYLON = {}));
  22328. var BABYLON;
  22329. (function (BABYLON) {
  22330. var Skeleton = (function () {
  22331. function Skeleton(name, id, scene) {
  22332. this.name = name;
  22333. this.id = id;
  22334. this.bones = new Array();
  22335. this._isDirty = true;
  22336. this._identity = BABYLON.Matrix.Identity();
  22337. this._ranges = new Array();
  22338. this.bones = [];
  22339. this._scene = scene;
  22340. scene.skeletons.push(this);
  22341. this.prepare();
  22342. //make sure it will recalculate the matrix next time prepare is called.
  22343. this._isDirty = true;
  22344. }
  22345. // Members
  22346. Skeleton.prototype.getTransformMatrices = function () {
  22347. return this._transformMatrices;
  22348. };
  22349. Skeleton.prototype.getScene = function () {
  22350. return this._scene;
  22351. };
  22352. // Methods
  22353. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22354. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22355. };
  22356. Skeleton.prototype.deleteAnimationRange = function (name) {
  22357. for (var index = 0; index < this._ranges.length; index++) {
  22358. if (this._ranges[index].name === name) {
  22359. this._ranges.splice(index, 1);
  22360. return;
  22361. }
  22362. }
  22363. };
  22364. Skeleton.prototype.getAnimationRange = function (name) {
  22365. for (var index = 0; index < this._ranges.length; index++) {
  22366. if (this._ranges[index].name === name) {
  22367. return this._ranges[index];
  22368. }
  22369. }
  22370. return null;
  22371. };
  22372. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22373. var range = this.getAnimationRange(name);
  22374. if (!range) {
  22375. return null;
  22376. }
  22377. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22378. };
  22379. Skeleton.prototype._markAsDirty = function () {
  22380. this._isDirty = true;
  22381. };
  22382. Skeleton.prototype.prepare = function () {
  22383. if (!this._isDirty) {
  22384. return;
  22385. }
  22386. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22387. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22388. }
  22389. for (var index = 0; index < this.bones.length; index++) {
  22390. var bone = this.bones[index];
  22391. var parentBone = bone.getParent();
  22392. if (parentBone) {
  22393. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22394. }
  22395. else {
  22396. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22397. }
  22398. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22399. }
  22400. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22401. this._isDirty = false;
  22402. this._scene._activeBones += this.bones.length;
  22403. };
  22404. Skeleton.prototype.getAnimatables = function () {
  22405. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22406. this._animatables = [];
  22407. for (var index = 0; index < this.bones.length; index++) {
  22408. this._animatables.push(this.bones[index]);
  22409. }
  22410. }
  22411. return this._animatables;
  22412. };
  22413. Skeleton.prototype.clone = function (name, id) {
  22414. var result = new Skeleton(name, id || name, this._scene);
  22415. for (var index = 0; index < this.bones.length; index++) {
  22416. var source = this.bones[index];
  22417. var parentBone = null;
  22418. if (source.getParent()) {
  22419. var parentIndex = this.bones.indexOf(source.getParent());
  22420. parentBone = result.bones[parentIndex];
  22421. }
  22422. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22423. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22424. }
  22425. return result;
  22426. };
  22427. Skeleton.prototype.dispose = function () {
  22428. // Animations
  22429. this.getScene().stopAnimation(this);
  22430. // Remove from scene
  22431. this.getScene().removeSkeleton(this);
  22432. };
  22433. return Skeleton;
  22434. })();
  22435. BABYLON.Skeleton = Skeleton;
  22436. })(BABYLON || (BABYLON = {}));
  22437. var BABYLON;
  22438. (function (BABYLON) {
  22439. var PostProcess = (function () {
  22440. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22442. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22443. this.name = name;
  22444. this.width = -1;
  22445. this.height = -1;
  22446. this._reusable = false;
  22447. this._textures = new BABYLON.SmartArray(2);
  22448. this._currentRenderTextureInd = 0;
  22449. if (camera != null) {
  22450. this._camera = camera;
  22451. this._scene = camera.getScene();
  22452. camera.attachPostProcess(this);
  22453. this._engine = this._scene.getEngine();
  22454. }
  22455. else {
  22456. this._engine = engine;
  22457. }
  22458. this._renderRatio = ratio;
  22459. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22460. this._reusable = reusable || false;
  22461. this._textureType = textureType;
  22462. samplers = samplers || [];
  22463. samplers.push("textureSampler");
  22464. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22465. }
  22466. PostProcess.prototype.isReusable = function () {
  22467. return this._reusable;
  22468. };
  22469. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22470. camera = camera || this._camera;
  22471. var scene = camera.getScene();
  22472. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22473. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22474. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22475. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22476. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22477. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22478. if (this._textures.length > 0) {
  22479. for (var i = 0; i < this._textures.length; i++) {
  22480. this._engine._releaseTexture(this._textures.data[i]);
  22481. }
  22482. this._textures.reset();
  22483. }
  22484. this.width = desiredWidth;
  22485. this.height = desiredHeight;
  22486. 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 }));
  22487. if (this._reusable) {
  22488. 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 }));
  22489. }
  22490. if (this.onSizeChanged) {
  22491. this.onSizeChanged();
  22492. }
  22493. }
  22494. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22495. if (this.onActivate) {
  22496. this.onActivate(camera);
  22497. }
  22498. // Clear
  22499. if (this.clearColor) {
  22500. this._engine.clear(this.clearColor, true, true);
  22501. }
  22502. else {
  22503. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22504. }
  22505. if (this._reusable) {
  22506. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22507. }
  22508. };
  22509. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22510. get: function () {
  22511. return this._effect.isSupported;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. PostProcess.prototype.apply = function () {
  22517. // Check
  22518. if (!this._effect.isReady())
  22519. return null;
  22520. // States
  22521. this._engine.enableEffect(this._effect);
  22522. this._engine.setState(false);
  22523. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22524. this._engine.setDepthBuffer(false);
  22525. this._engine.setDepthWrite(false);
  22526. // Texture
  22527. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22528. // Parameters
  22529. if (this.onApply) {
  22530. this.onApply(this._effect);
  22531. }
  22532. return this._effect;
  22533. };
  22534. PostProcess.prototype.dispose = function (camera) {
  22535. camera = camera || this._camera;
  22536. if (this._textures.length > 0) {
  22537. for (var i = 0; i < this._textures.length; i++) {
  22538. this._engine._releaseTexture(this._textures.data[i]);
  22539. }
  22540. this._textures.reset();
  22541. }
  22542. if (!camera) {
  22543. return;
  22544. }
  22545. camera.detachPostProcess(this);
  22546. var index = camera._postProcesses.indexOf(this);
  22547. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22548. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22549. }
  22550. };
  22551. return PostProcess;
  22552. })();
  22553. BABYLON.PostProcess = PostProcess;
  22554. })(BABYLON || (BABYLON = {}));
  22555. var BABYLON;
  22556. (function (BABYLON) {
  22557. var PostProcessManager = (function () {
  22558. function PostProcessManager(scene) {
  22559. this._vertexDeclaration = [2];
  22560. this._vertexStrideSize = 2 * 4;
  22561. this._scene = scene;
  22562. }
  22563. PostProcessManager.prototype._prepareBuffers = function () {
  22564. if (this._vertexBuffer) {
  22565. return;
  22566. }
  22567. // VBO
  22568. var vertices = [];
  22569. vertices.push(1, 1);
  22570. vertices.push(-1, 1);
  22571. vertices.push(-1, -1);
  22572. vertices.push(1, -1);
  22573. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22574. // Indices
  22575. var indices = [];
  22576. indices.push(0);
  22577. indices.push(1);
  22578. indices.push(2);
  22579. indices.push(0);
  22580. indices.push(2);
  22581. indices.push(3);
  22582. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22583. };
  22584. // Methods
  22585. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22586. var postProcesses = this._scene.activeCamera._postProcesses;
  22587. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22588. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22589. return false;
  22590. }
  22591. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22592. return true;
  22593. };
  22594. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22595. var engine = this._scene.getEngine();
  22596. for (var index = 0; index < postProcesses.length; index++) {
  22597. if (index < postProcesses.length - 1) {
  22598. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22599. }
  22600. else {
  22601. if (targetTexture) {
  22602. engine.bindFramebuffer(targetTexture);
  22603. }
  22604. else {
  22605. engine.restoreDefaultFramebuffer();
  22606. }
  22607. }
  22608. var pp = postProcesses[index];
  22609. var effect = pp.apply();
  22610. if (effect) {
  22611. if (pp.onBeforeRender) {
  22612. pp.onBeforeRender(effect);
  22613. }
  22614. // VBOs
  22615. this._prepareBuffers();
  22616. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22617. // Draw order
  22618. engine.draw(true, 0, 6);
  22619. if (pp.onAfterRender) {
  22620. pp.onAfterRender(effect);
  22621. }
  22622. }
  22623. }
  22624. // Restore depth buffer
  22625. engine.setDepthBuffer(true);
  22626. engine.setDepthWrite(true);
  22627. };
  22628. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22629. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22630. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22631. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22632. return;
  22633. }
  22634. var engine = this._scene.getEngine();
  22635. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22636. if (index < postProcessesTakenIndices.length - 1) {
  22637. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22638. }
  22639. else {
  22640. if (targetTexture) {
  22641. engine.bindFramebuffer(targetTexture, faceIndex);
  22642. }
  22643. else {
  22644. engine.restoreDefaultFramebuffer();
  22645. }
  22646. }
  22647. if (doNotPresent) {
  22648. break;
  22649. }
  22650. var pp = postProcesses[postProcessesTakenIndices[index]];
  22651. var effect = pp.apply();
  22652. if (effect) {
  22653. if (pp.onBeforeRender) {
  22654. pp.onBeforeRender(effect);
  22655. }
  22656. // VBOs
  22657. this._prepareBuffers();
  22658. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22659. // Draw order
  22660. engine.draw(true, 0, 6);
  22661. if (pp.onAfterRender) {
  22662. pp.onAfterRender(effect);
  22663. }
  22664. }
  22665. }
  22666. // Restore depth buffer
  22667. engine.setDepthBuffer(true);
  22668. engine.setDepthWrite(true);
  22669. };
  22670. PostProcessManager.prototype.dispose = function () {
  22671. if (this._vertexBuffer) {
  22672. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22673. this._vertexBuffer = null;
  22674. }
  22675. if (this._indexBuffer) {
  22676. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22677. this._indexBuffer = null;
  22678. }
  22679. };
  22680. return PostProcessManager;
  22681. })();
  22682. BABYLON.PostProcessManager = PostProcessManager;
  22683. })(BABYLON || (BABYLON = {}));
  22684. var BABYLON;
  22685. (function (BABYLON) {
  22686. var PassPostProcess = (function (_super) {
  22687. __extends(PassPostProcess, _super);
  22688. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22689. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22690. }
  22691. return PassPostProcess;
  22692. })(BABYLON.PostProcess);
  22693. BABYLON.PassPostProcess = PassPostProcess;
  22694. })(BABYLON || (BABYLON = {}));
  22695. var BABYLON;
  22696. (function (BABYLON) {
  22697. var PhysicsEngine = (function () {
  22698. function PhysicsEngine(plugin) {
  22699. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22700. }
  22701. PhysicsEngine.prototype._initialize = function (gravity) {
  22702. this._currentPlugin.initialize();
  22703. this._setGravity(gravity);
  22704. };
  22705. PhysicsEngine.prototype._runOneStep = function (delta) {
  22706. if (delta > 0.1) {
  22707. delta = 0.1;
  22708. }
  22709. else if (delta <= 0) {
  22710. delta = 1.0 / 60.0;
  22711. }
  22712. this._currentPlugin.runOneStep(delta);
  22713. };
  22714. PhysicsEngine.prototype._setGravity = function (gravity) {
  22715. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22716. this._currentPlugin.setGravity(this.gravity);
  22717. };
  22718. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22719. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22720. };
  22721. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22722. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22723. };
  22724. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22725. this._currentPlugin.unregisterMesh(mesh);
  22726. };
  22727. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22728. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22729. };
  22730. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22731. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22732. };
  22733. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22734. this._currentPlugin.updateBodyPosition(mesh);
  22735. };
  22736. PhysicsEngine.prototype.dispose = function () {
  22737. this._currentPlugin.dispose();
  22738. };
  22739. PhysicsEngine.prototype.isSupported = function () {
  22740. return this._currentPlugin.isSupported();
  22741. };
  22742. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22743. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22744. };
  22745. // Statics
  22746. PhysicsEngine.NoImpostor = 0;
  22747. PhysicsEngine.SphereImpostor = 1;
  22748. PhysicsEngine.BoxImpostor = 2;
  22749. PhysicsEngine.PlaneImpostor = 3;
  22750. PhysicsEngine.MeshImpostor = 4;
  22751. PhysicsEngine.CapsuleImpostor = 5;
  22752. PhysicsEngine.ConeImpostor = 6;
  22753. PhysicsEngine.CylinderImpostor = 7;
  22754. PhysicsEngine.ConvexHullImpostor = 8;
  22755. PhysicsEngine.HeightmapImpostor = 9;
  22756. PhysicsEngine.Epsilon = 0.001;
  22757. return PhysicsEngine;
  22758. })();
  22759. BABYLON.PhysicsEngine = PhysicsEngine;
  22760. })(BABYLON || (BABYLON = {}));
  22761. var BABYLON;
  22762. (function (BABYLON) {
  22763. var VertexData = (function () {
  22764. function VertexData() {
  22765. }
  22766. VertexData.prototype.set = function (data, kind) {
  22767. switch (kind) {
  22768. case BABYLON.VertexBuffer.PositionKind:
  22769. this.positions = data;
  22770. break;
  22771. case BABYLON.VertexBuffer.NormalKind:
  22772. this.normals = data;
  22773. break;
  22774. case BABYLON.VertexBuffer.UVKind:
  22775. this.uvs = data;
  22776. break;
  22777. case BABYLON.VertexBuffer.UV2Kind:
  22778. this.uvs2 = data;
  22779. break;
  22780. case BABYLON.VertexBuffer.UV3Kind:
  22781. this.uvs3 = data;
  22782. break;
  22783. case BABYLON.VertexBuffer.UV4Kind:
  22784. this.uvs4 = data;
  22785. break;
  22786. case BABYLON.VertexBuffer.UV5Kind:
  22787. this.uvs5 = data;
  22788. break;
  22789. case BABYLON.VertexBuffer.UV6Kind:
  22790. this.uvs6 = data;
  22791. break;
  22792. case BABYLON.VertexBuffer.ColorKind:
  22793. this.colors = data;
  22794. break;
  22795. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22796. this.matricesIndices = data;
  22797. break;
  22798. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22799. this.matricesWeights = data;
  22800. break;
  22801. }
  22802. };
  22803. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22804. this._applyTo(mesh, updatable);
  22805. };
  22806. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22807. this._applyTo(geometry, updatable);
  22808. };
  22809. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22810. this._update(mesh);
  22811. };
  22812. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22813. this._update(geometry);
  22814. };
  22815. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22816. if (this.positions) {
  22817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22818. }
  22819. if (this.normals) {
  22820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22821. }
  22822. if (this.uvs) {
  22823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22824. }
  22825. if (this.uvs2) {
  22826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22827. }
  22828. if (this.uvs3) {
  22829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22830. }
  22831. if (this.uvs4) {
  22832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22833. }
  22834. if (this.uvs5) {
  22835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22836. }
  22837. if (this.uvs6) {
  22838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22839. }
  22840. if (this.colors) {
  22841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22842. }
  22843. if (this.matricesIndices) {
  22844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22845. }
  22846. if (this.matricesWeights) {
  22847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22848. }
  22849. if (this.indices) {
  22850. meshOrGeometry.setIndices(this.indices);
  22851. }
  22852. };
  22853. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22854. if (this.positions) {
  22855. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22856. }
  22857. if (this.normals) {
  22858. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22859. }
  22860. if (this.uvs) {
  22861. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22862. }
  22863. if (this.uvs2) {
  22864. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22865. }
  22866. if (this.uvs3) {
  22867. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22868. }
  22869. if (this.uvs4) {
  22870. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22871. }
  22872. if (this.uvs5) {
  22873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22874. }
  22875. if (this.uvs6) {
  22876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22877. }
  22878. if (this.colors) {
  22879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22880. }
  22881. if (this.matricesIndices) {
  22882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22883. }
  22884. if (this.matricesWeights) {
  22885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22886. }
  22887. if (this.indices) {
  22888. meshOrGeometry.setIndices(this.indices);
  22889. }
  22890. };
  22891. VertexData.prototype.transform = function (matrix) {
  22892. var transformed = BABYLON.Vector3.Zero();
  22893. var index;
  22894. if (this.positions) {
  22895. var position = BABYLON.Vector3.Zero();
  22896. for (index = 0; index < this.positions.length; index += 3) {
  22897. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22898. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22899. this.positions[index] = transformed.x;
  22900. this.positions[index + 1] = transformed.y;
  22901. this.positions[index + 2] = transformed.z;
  22902. }
  22903. }
  22904. if (this.normals) {
  22905. var normal = BABYLON.Vector3.Zero();
  22906. for (index = 0; index < this.normals.length; index += 3) {
  22907. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22908. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22909. this.normals[index] = transformed.x;
  22910. this.normals[index + 1] = transformed.y;
  22911. this.normals[index + 2] = transformed.z;
  22912. }
  22913. }
  22914. };
  22915. VertexData.prototype.merge = function (other) {
  22916. var index;
  22917. if (other.indices) {
  22918. if (!this.indices) {
  22919. this.indices = [];
  22920. }
  22921. var offset = this.positions ? this.positions.length / 3 : 0;
  22922. for (index = 0; index < other.indices.length; index++) {
  22923. this.indices.push(other.indices[index] + offset);
  22924. }
  22925. }
  22926. if (other.positions) {
  22927. if (!this.positions) {
  22928. this.positions = [];
  22929. }
  22930. for (index = 0; index < other.positions.length; index++) {
  22931. this.positions.push(other.positions[index]);
  22932. }
  22933. }
  22934. if (other.normals) {
  22935. if (!this.normals) {
  22936. this.normals = [];
  22937. }
  22938. for (index = 0; index < other.normals.length; index++) {
  22939. this.normals.push(other.normals[index]);
  22940. }
  22941. }
  22942. if (other.uvs) {
  22943. if (!this.uvs) {
  22944. this.uvs = [];
  22945. }
  22946. for (index = 0; index < other.uvs.length; index++) {
  22947. this.uvs.push(other.uvs[index]);
  22948. }
  22949. }
  22950. if (other.uvs2) {
  22951. if (!this.uvs2) {
  22952. this.uvs2 = [];
  22953. }
  22954. for (index = 0; index < other.uvs2.length; index++) {
  22955. this.uvs2.push(other.uvs2[index]);
  22956. }
  22957. }
  22958. if (other.uvs3) {
  22959. if (!this.uvs3) {
  22960. this.uvs3 = [];
  22961. }
  22962. for (index = 0; index < other.uvs3.length; index++) {
  22963. this.uvs3.push(other.uvs3[index]);
  22964. }
  22965. }
  22966. if (other.uvs4) {
  22967. if (!this.uvs4) {
  22968. this.uvs4 = [];
  22969. }
  22970. for (index = 0; index < other.uvs4.length; index++) {
  22971. this.uvs4.push(other.uvs4[index]);
  22972. }
  22973. }
  22974. if (other.uvs5) {
  22975. if (!this.uvs5) {
  22976. this.uvs5 = [];
  22977. }
  22978. for (index = 0; index < other.uvs5.length; index++) {
  22979. this.uvs5.push(other.uvs5[index]);
  22980. }
  22981. }
  22982. if (other.uvs6) {
  22983. if (!this.uvs6) {
  22984. this.uvs6 = [];
  22985. }
  22986. for (index = 0; index < other.uvs6.length; index++) {
  22987. this.uvs6.push(other.uvs6[index]);
  22988. }
  22989. }
  22990. if (other.matricesIndices) {
  22991. if (!this.matricesIndices) {
  22992. this.matricesIndices = [];
  22993. }
  22994. for (index = 0; index < other.matricesIndices.length; index++) {
  22995. this.matricesIndices.push(other.matricesIndices[index]);
  22996. }
  22997. }
  22998. if (other.matricesWeights) {
  22999. if (!this.matricesWeights) {
  23000. this.matricesWeights = [];
  23001. }
  23002. for (index = 0; index < other.matricesWeights.length; index++) {
  23003. this.matricesWeights.push(other.matricesWeights[index]);
  23004. }
  23005. }
  23006. if (other.colors) {
  23007. if (!this.colors) {
  23008. this.colors = [];
  23009. }
  23010. for (index = 0; index < other.colors.length; index++) {
  23011. this.colors.push(other.colors[index]);
  23012. }
  23013. }
  23014. };
  23015. // Statics
  23016. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23017. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23018. };
  23019. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23020. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23021. };
  23022. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23023. var result = new VertexData();
  23024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23025. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23026. }
  23027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23028. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23029. }
  23030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23031. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23032. }
  23033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23034. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23035. }
  23036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23037. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23038. }
  23039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23040. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23041. }
  23042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23043. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23044. }
  23045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23046. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23047. }
  23048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23049. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23050. }
  23051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23052. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23053. }
  23054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23055. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23056. }
  23057. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23058. return result;
  23059. };
  23060. VertexData.CreateRibbon = function (options) {
  23061. var pathArray = options.pathArray;
  23062. var closeArray = options.closeArray || false;
  23063. var closePath = options.closePath || false;
  23064. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23065. var offset = options.offset || defaultOffset;
  23066. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23068. var positions = [];
  23069. var indices = [];
  23070. var normals = [];
  23071. var uvs = [];
  23072. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23073. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23074. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23075. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23076. var minlg; // minimal length among all paths from pathArray
  23077. var lg = []; // array of path lengths : nb of vertex per path
  23078. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23079. var p; // path iterator
  23080. var i; // point iterator
  23081. var j; // point iterator
  23082. // if single path in pathArray
  23083. if (pathArray.length < 2) {
  23084. var ar1 = [];
  23085. var ar2 = [];
  23086. for (i = 0; i < pathArray[0].length - offset; i++) {
  23087. ar1.push(pathArray[0][i]);
  23088. ar2.push(pathArray[0][i + offset]);
  23089. }
  23090. pathArray = [ar1, ar2];
  23091. }
  23092. // positions and horizontal distances (u)
  23093. var idc = 0;
  23094. var closePathCorr = (closePath) ? 1 : 0;
  23095. var path;
  23096. var l;
  23097. minlg = pathArray[0].length;
  23098. var vectlg;
  23099. var dist;
  23100. for (p = 0; p < pathArray.length; p++) {
  23101. uTotalDistance[p] = 0;
  23102. us[p] = [0];
  23103. path = pathArray[p];
  23104. l = path.length;
  23105. minlg = (minlg < l) ? minlg : l;
  23106. j = 0;
  23107. while (j < l) {
  23108. positions.push(path[j].x, path[j].y, path[j].z);
  23109. if (j > 0) {
  23110. vectlg = path[j].subtract(path[j - 1]).length();
  23111. dist = vectlg + uTotalDistance[p];
  23112. us[p].push(dist);
  23113. uTotalDistance[p] = dist;
  23114. }
  23115. j++;
  23116. }
  23117. if (closePath) {
  23118. j--;
  23119. positions.push(path[0].x, path[0].y, path[0].z);
  23120. vectlg = path[j].subtract(path[0]).length();
  23121. dist = vectlg + uTotalDistance[p];
  23122. us[p].push(dist);
  23123. uTotalDistance[p] = dist;
  23124. }
  23125. lg[p] = l + closePathCorr;
  23126. idx[p] = idc;
  23127. idc += (l + closePathCorr);
  23128. }
  23129. // vertical distances (v)
  23130. var path1;
  23131. var path2;
  23132. var vertex1;
  23133. var vertex2;
  23134. for (i = 0; i < minlg + closePathCorr; i++) {
  23135. vTotalDistance[i] = 0;
  23136. vs[i] = [0];
  23137. for (p = 0; p < pathArray.length - 1; p++) {
  23138. path1 = pathArray[p];
  23139. path2 = pathArray[p + 1];
  23140. if (i === minlg) {
  23141. vertex1 = path1[0];
  23142. vertex2 = path2[0];
  23143. }
  23144. else {
  23145. vertex1 = path1[i];
  23146. vertex2 = path2[i];
  23147. }
  23148. vectlg = vertex2.subtract(vertex1).length();
  23149. dist = vectlg + vTotalDistance[i];
  23150. vs[i].push(dist);
  23151. vTotalDistance[i] = dist;
  23152. }
  23153. if (closeArray) {
  23154. path1 = pathArray[p];
  23155. path2 = pathArray[0];
  23156. if (i === minlg) {
  23157. vertex2 = path2[0];
  23158. }
  23159. vectlg = vertex2.subtract(vertex1).length();
  23160. dist = vectlg + vTotalDistance[i];
  23161. vTotalDistance[i] = dist;
  23162. }
  23163. }
  23164. // uvs
  23165. var u;
  23166. var v;
  23167. for (p = 0; p < pathArray.length; p++) {
  23168. for (i = 0; i < minlg + closePathCorr; i++) {
  23169. u = us[p][i] / uTotalDistance[p];
  23170. v = vs[i][p] / vTotalDistance[i];
  23171. uvs.push(u, v);
  23172. }
  23173. }
  23174. // indices
  23175. p = 0; // path index
  23176. var pi = 0; // positions array index
  23177. var l1 = lg[p] - 1; // path1 length
  23178. var l2 = lg[p + 1] - 1; // path2 length
  23179. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23180. var shft = idx[1] - idx[0]; // shift
  23181. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23182. while (pi <= min && p < path1nb) {
  23183. // 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
  23184. indices.push(pi, pi + shft, pi + 1);
  23185. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23186. pi += 1;
  23187. if (pi === min) {
  23188. p++;
  23189. if (p === lg.length - 1) {
  23190. shft = idx[0] - idx[p];
  23191. l1 = lg[p] - 1;
  23192. l2 = lg[0] - 1;
  23193. }
  23194. else {
  23195. shft = idx[p + 1] - idx[p];
  23196. l1 = lg[p] - 1;
  23197. l2 = lg[p + 1] - 1;
  23198. }
  23199. pi = idx[p];
  23200. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23201. }
  23202. }
  23203. // normals
  23204. VertexData.ComputeNormals(positions, indices, normals);
  23205. if (closePath) {
  23206. var indexFirst = 0;
  23207. var indexLast = 0;
  23208. for (p = 0; p < pathArray.length; p++) {
  23209. indexFirst = idx[p] * 3;
  23210. if (p + 1 < pathArray.length) {
  23211. indexLast = (idx[p + 1] - 1) * 3;
  23212. }
  23213. else {
  23214. indexLast = normals.length - 3;
  23215. }
  23216. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23217. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23218. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23219. normals[indexLast] = normals[indexFirst];
  23220. normals[indexLast + 1] = normals[indexFirst + 1];
  23221. normals[indexLast + 2] = normals[indexFirst + 2];
  23222. }
  23223. }
  23224. // sides
  23225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23226. // Result
  23227. var vertexData = new VertexData();
  23228. vertexData.indices = indices;
  23229. vertexData.positions = positions;
  23230. vertexData.normals = normals;
  23231. vertexData.uvs = uvs;
  23232. if (closePath) {
  23233. vertexData._idx = idx;
  23234. }
  23235. return vertexData;
  23236. };
  23237. VertexData.CreateBox = function (options) {
  23238. var normalsSource = [
  23239. new BABYLON.Vector3(0, 0, 1),
  23240. new BABYLON.Vector3(0, 0, -1),
  23241. new BABYLON.Vector3(1, 0, 0),
  23242. new BABYLON.Vector3(-1, 0, 0),
  23243. new BABYLON.Vector3(0, 1, 0),
  23244. new BABYLON.Vector3(0, -1, 0)
  23245. ];
  23246. var indices = [];
  23247. var positions = [];
  23248. var normals = [];
  23249. var uvs = [];
  23250. var width = options.width || options.size || 1;
  23251. var height = options.height || options.size || 1;
  23252. var depth = options.depth || options.size || 1;
  23253. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23254. var faceUV = options.faceUV || new Array(6);
  23255. var faceColors = options.faceColors;
  23256. var colors = [];
  23257. // default face colors and UV if undefined
  23258. for (var f = 0; f < 6; f++) {
  23259. if (faceUV[f] === undefined) {
  23260. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23261. }
  23262. if (faceColors && faceColors[f] === undefined) {
  23263. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23264. }
  23265. }
  23266. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23267. // Create each face in turn.
  23268. for (var index = 0; index < normalsSource.length; index++) {
  23269. var normal = normalsSource[index];
  23270. // Get two vectors perpendicular to the face normal and to each other.
  23271. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23272. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23273. // Six indices (two triangles) per face.
  23274. var verticesLength = positions.length / 3;
  23275. indices.push(verticesLength);
  23276. indices.push(verticesLength + 1);
  23277. indices.push(verticesLength + 2);
  23278. indices.push(verticesLength);
  23279. indices.push(verticesLength + 2);
  23280. indices.push(verticesLength + 3);
  23281. // Four vertices per face.
  23282. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23283. positions.push(vertex.x, vertex.y, vertex.z);
  23284. normals.push(normal.x, normal.y, normal.z);
  23285. uvs.push(faceUV[index].z, faceUV[index].w);
  23286. if (faceColors) {
  23287. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23288. }
  23289. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23290. positions.push(vertex.x, vertex.y, vertex.z);
  23291. normals.push(normal.x, normal.y, normal.z);
  23292. uvs.push(faceUV[index].x, faceUV[index].w);
  23293. if (faceColors) {
  23294. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23295. }
  23296. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23297. positions.push(vertex.x, vertex.y, vertex.z);
  23298. normals.push(normal.x, normal.y, normal.z);
  23299. uvs.push(faceUV[index].x, faceUV[index].y);
  23300. if (faceColors) {
  23301. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23302. }
  23303. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23304. positions.push(vertex.x, vertex.y, vertex.z);
  23305. normals.push(normal.x, normal.y, normal.z);
  23306. uvs.push(faceUV[index].z, faceUV[index].y);
  23307. if (faceColors) {
  23308. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23309. }
  23310. }
  23311. // sides
  23312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23313. // Result
  23314. var vertexData = new VertexData();
  23315. vertexData.indices = indices;
  23316. vertexData.positions = positions;
  23317. vertexData.normals = normals;
  23318. vertexData.uvs = uvs;
  23319. if (faceColors) {
  23320. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23321. vertexData.colors = totalColors;
  23322. }
  23323. return vertexData;
  23324. };
  23325. VertexData.CreateSphere = function (options) {
  23326. var segments = options.segments || 32;
  23327. var diameterX = options.diameterX || options.diameter || 1;
  23328. var diameterY = options.diameterY || options.diameter || 1;
  23329. var diameterZ = options.diameterZ || options.diameter || 1;
  23330. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23331. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23332. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23333. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23334. var totalZRotationSteps = 2 + segments;
  23335. var totalYRotationSteps = 2 * totalZRotationSteps;
  23336. var indices = [];
  23337. var positions = [];
  23338. var normals = [];
  23339. var uvs = [];
  23340. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23341. var normalizedZ = zRotationStep / totalZRotationSteps;
  23342. var angleZ = normalizedZ * Math.PI * slice;
  23343. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23344. var normalizedY = yRotationStep / totalYRotationSteps;
  23345. var angleY = normalizedY * Math.PI * 2 * arc;
  23346. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23347. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23348. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23349. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23350. var vertex = complete.multiply(radius);
  23351. var normal = BABYLON.Vector3.Normalize(vertex);
  23352. positions.push(vertex.x, vertex.y, vertex.z);
  23353. normals.push(normal.x, normal.y, normal.z);
  23354. uvs.push(normalizedY, normalizedZ);
  23355. }
  23356. if (zRotationStep > 0) {
  23357. var verticesCount = positions.length / 3;
  23358. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23359. indices.push((firstIndex));
  23360. indices.push((firstIndex + 1));
  23361. indices.push(firstIndex + totalYRotationSteps + 1);
  23362. indices.push((firstIndex + totalYRotationSteps + 1));
  23363. indices.push((firstIndex + 1));
  23364. indices.push((firstIndex + totalYRotationSteps + 2));
  23365. }
  23366. }
  23367. }
  23368. // Sides
  23369. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23370. // Result
  23371. var vertexData = new VertexData();
  23372. vertexData.indices = indices;
  23373. vertexData.positions = positions;
  23374. vertexData.normals = normals;
  23375. vertexData.uvs = uvs;
  23376. return vertexData;
  23377. };
  23378. // Cylinder and cone
  23379. VertexData.CreateCylinder = function (options) {
  23380. var height = options.height || 2;
  23381. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23382. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23383. var tessellation = options.tessellation || 24;
  23384. var subdivisions = options.subdivisions || 1;
  23385. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23386. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23387. var faceUV = options.faceUV || new Array(3);
  23388. var faceColors = options.faceColors;
  23389. // default face colors and UV if undefined
  23390. for (var f = 0; f < 3; f++) {
  23391. if (faceColors && faceColors[f] === undefined) {
  23392. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23393. }
  23394. if (faceUV && faceUV[f] === undefined) {
  23395. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23396. }
  23397. }
  23398. var indices = [];
  23399. var positions = [];
  23400. var normals = [];
  23401. var uvs = [];
  23402. var colors = [];
  23403. var angle_step = Math.PI * 2 * arc / tessellation;
  23404. var angle;
  23405. var h;
  23406. var radius;
  23407. var tan = (diameterBottom - diameterTop) / 2 / height;
  23408. var ringVertex = BABYLON.Vector3.Zero();
  23409. var ringNormal = BABYLON.Vector3.Zero();
  23410. // positions, normals, uvs
  23411. var i;
  23412. var j;
  23413. for (i = 0; i <= subdivisions; i++) {
  23414. h = i / subdivisions;
  23415. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23416. for (j = 0; j <= tessellation; j++) {
  23417. angle = j * angle_step;
  23418. ringVertex.x = Math.cos(-angle) * radius;
  23419. ringVertex.y = -height / 2 + h * height;
  23420. ringVertex.z = Math.sin(-angle) * radius;
  23421. if (diameterTop === 0 && i === subdivisions) {
  23422. // if no top cap, reuse former normals
  23423. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23424. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23425. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23426. }
  23427. else {
  23428. ringNormal.x = ringVertex.x;
  23429. ringNormal.z = ringVertex.z;
  23430. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23431. ringNormal.normalize();
  23432. }
  23433. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23434. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23435. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23436. if (faceColors) {
  23437. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23438. }
  23439. }
  23440. }
  23441. // indices
  23442. for (i = 0; i < subdivisions; i++) {
  23443. for (j = 0; j < tessellation; j++) {
  23444. var i0 = i * (tessellation + 1) + j;
  23445. var i1 = (i + 1) * (tessellation + 1) + j;
  23446. var i2 = i * (tessellation + 1) + (j + 1);
  23447. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23448. indices.push(i0, i1, i2);
  23449. indices.push(i3, i2, i1);
  23450. }
  23451. }
  23452. // Caps
  23453. var createCylinderCap = function (isTop) {
  23454. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23455. if (radius === 0) {
  23456. return;
  23457. }
  23458. // Cap positions, normals & uvs
  23459. var angle;
  23460. var circleVector;
  23461. var i;
  23462. var u = (isTop) ? faceUV[2] : faceUV[0];
  23463. var c;
  23464. if (faceColors) {
  23465. c = (isTop) ? faceColors[2] : faceColors[0];
  23466. }
  23467. // cap center
  23468. var vbase = positions.length / 3;
  23469. var offset = isTop ? height / 2 : -height / 2;
  23470. var center = new BABYLON.Vector3(0, offset, 0);
  23471. positions.push(center.x, center.y, center.z);
  23472. normals.push(0, isTop ? 1 : -1, 0);
  23473. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23474. if (faceColors) {
  23475. colors.push(c.r, c.g, c.b, c.a);
  23476. }
  23477. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23478. for (i = 0; i <= tessellation; i++) {
  23479. angle = Math.PI * 2 * i * arc / tessellation;
  23480. var cos = Math.cos(-angle);
  23481. var sin = Math.sin(-angle);
  23482. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23483. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23484. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23485. normals.push(0, isTop ? 1 : -1, 0);
  23486. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23487. if (faceColors) {
  23488. colors.push(c.r, c.g, c.b, c.a);
  23489. }
  23490. }
  23491. // Cap indices
  23492. for (i = 0; i < tessellation; i++) {
  23493. if (!isTop) {
  23494. indices.push(vbase);
  23495. indices.push(vbase + (i + 1));
  23496. indices.push(vbase + (i + 2));
  23497. }
  23498. else {
  23499. indices.push(vbase);
  23500. indices.push(vbase + (i + 2));
  23501. indices.push(vbase + (i + 1));
  23502. }
  23503. }
  23504. };
  23505. // add caps to geometry
  23506. createCylinderCap(false);
  23507. createCylinderCap(true);
  23508. // Sides
  23509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23510. var vertexData = new VertexData();
  23511. vertexData.indices = indices;
  23512. vertexData.positions = positions;
  23513. vertexData.normals = normals;
  23514. vertexData.uvs = uvs;
  23515. if (faceColors) {
  23516. vertexData.colors = colors;
  23517. }
  23518. return vertexData;
  23519. };
  23520. VertexData.CreateTorus = function (options) {
  23521. var indices = [];
  23522. var positions = [];
  23523. var normals = [];
  23524. var uvs = [];
  23525. var diameter = options.diameter || 1;
  23526. var thickness = options.thickness || 0.5;
  23527. var tessellation = options.tessellation || 16;
  23528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23529. var stride = tessellation + 1;
  23530. for (var i = 0; i <= tessellation; i++) {
  23531. var u = i / tessellation;
  23532. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23533. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23534. for (var j = 0; j <= tessellation; j++) {
  23535. var v = 1 - j / tessellation;
  23536. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23537. var dx = Math.cos(innerAngle);
  23538. var dy = Math.sin(innerAngle);
  23539. // Create a vertex.
  23540. var normal = new BABYLON.Vector3(dx, dy, 0);
  23541. var position = normal.scale(thickness / 2);
  23542. var textureCoordinate = new BABYLON.Vector2(u, v);
  23543. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23544. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23545. positions.push(position.x, position.y, position.z);
  23546. normals.push(normal.x, normal.y, normal.z);
  23547. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23548. // And create indices for two triangles.
  23549. var nextI = (i + 1) % stride;
  23550. var nextJ = (j + 1) % stride;
  23551. indices.push(i * stride + j);
  23552. indices.push(i * stride + nextJ);
  23553. indices.push(nextI * stride + j);
  23554. indices.push(i * stride + nextJ);
  23555. indices.push(nextI * stride + nextJ);
  23556. indices.push(nextI * stride + j);
  23557. }
  23558. }
  23559. // Sides
  23560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23561. // Result
  23562. var vertexData = new VertexData();
  23563. vertexData.indices = indices;
  23564. vertexData.positions = positions;
  23565. vertexData.normals = normals;
  23566. vertexData.uvs = uvs;
  23567. return vertexData;
  23568. };
  23569. VertexData.CreateLines = function (options) {
  23570. var indices = [];
  23571. var positions = [];
  23572. var points = options.points;
  23573. for (var index = 0; index < points.length; index++) {
  23574. positions.push(points[index].x, points[index].y, points[index].z);
  23575. if (index > 0) {
  23576. indices.push(index - 1);
  23577. indices.push(index);
  23578. }
  23579. }
  23580. // Result
  23581. var vertexData = new VertexData();
  23582. vertexData.indices = indices;
  23583. vertexData.positions = positions;
  23584. return vertexData;
  23585. };
  23586. VertexData.CreateDashedLines = function (options) {
  23587. var dashSize = options.dashSize || 3;
  23588. var gapSize = options.gapSize || 1;
  23589. var dashNb = options.dashNb || 200;
  23590. var points = options.points;
  23591. var positions = new Array();
  23592. var indices = new Array();
  23593. var curvect = BABYLON.Vector3.Zero();
  23594. var lg = 0;
  23595. var nb = 0;
  23596. var shft = 0;
  23597. var dashshft = 0;
  23598. var curshft = 0;
  23599. var idx = 0;
  23600. var i = 0;
  23601. for (i = 0; i < points.length - 1; i++) {
  23602. points[i + 1].subtractToRef(points[i], curvect);
  23603. lg += curvect.length();
  23604. }
  23605. shft = lg / dashNb;
  23606. dashshft = dashSize * shft / (dashSize + gapSize);
  23607. for (i = 0; i < points.length - 1; i++) {
  23608. points[i + 1].subtractToRef(points[i], curvect);
  23609. nb = Math.floor(curvect.length() / shft);
  23610. curvect.normalize();
  23611. for (var j = 0; j < nb; j++) {
  23612. curshft = shft * j;
  23613. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23614. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23615. indices.push(idx, idx + 1);
  23616. idx += 2;
  23617. }
  23618. }
  23619. // Result
  23620. var vertexData = new VertexData();
  23621. vertexData.positions = positions;
  23622. vertexData.indices = indices;
  23623. return vertexData;
  23624. };
  23625. VertexData.CreateGround = function (options) {
  23626. var indices = [];
  23627. var positions = [];
  23628. var normals = [];
  23629. var uvs = [];
  23630. var row, col;
  23631. var width = options.width || 1;
  23632. var height = options.height || 1;
  23633. var subdivisions = options.subdivisions || 1;
  23634. for (row = 0; row <= subdivisions; row++) {
  23635. for (col = 0; col <= subdivisions; col++) {
  23636. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23637. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23638. positions.push(position.x, position.y, position.z);
  23639. normals.push(normal.x, normal.y, normal.z);
  23640. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23641. }
  23642. }
  23643. for (row = 0; row < subdivisions; row++) {
  23644. for (col = 0; col < subdivisions; col++) {
  23645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23646. indices.push(col + 1 + row * (subdivisions + 1));
  23647. indices.push(col + row * (subdivisions + 1));
  23648. indices.push(col + (row + 1) * (subdivisions + 1));
  23649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23650. indices.push(col + row * (subdivisions + 1));
  23651. }
  23652. }
  23653. // Result
  23654. var vertexData = new VertexData();
  23655. vertexData.indices = indices;
  23656. vertexData.positions = positions;
  23657. vertexData.normals = normals;
  23658. vertexData.uvs = uvs;
  23659. return vertexData;
  23660. };
  23661. VertexData.CreateTiledGround = function (options) {
  23662. var xmin = options.xmin;
  23663. var zmin = options.zmin;
  23664. var xmax = options.xmax;
  23665. var zmax = options.zmax;
  23666. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23667. var precision = options.precision || { w: 1, h: 1 };
  23668. var indices = [];
  23669. var positions = [];
  23670. var normals = [];
  23671. var uvs = [];
  23672. var row, col, tileRow, tileCol;
  23673. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23674. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23675. precision.w = (precision.w < 1) ? 1 : precision.w;
  23676. precision.h = (precision.h < 1) ? 1 : precision.h;
  23677. var tileSize = {
  23678. 'w': (xmax - xmin) / subdivisions.w,
  23679. 'h': (zmax - zmin) / subdivisions.h
  23680. };
  23681. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23682. // Indices
  23683. var base = positions.length / 3;
  23684. var rowLength = precision.w + 1;
  23685. for (row = 0; row < precision.h; row++) {
  23686. for (col = 0; col < precision.w; col++) {
  23687. var square = [
  23688. base + col + row * rowLength,
  23689. base + (col + 1) + row * rowLength,
  23690. base + (col + 1) + (row + 1) * rowLength,
  23691. base + col + (row + 1) * rowLength
  23692. ];
  23693. indices.push(square[1]);
  23694. indices.push(square[2]);
  23695. indices.push(square[3]);
  23696. indices.push(square[0]);
  23697. indices.push(square[1]);
  23698. indices.push(square[3]);
  23699. }
  23700. }
  23701. // Position, normals and uvs
  23702. var position = BABYLON.Vector3.Zero();
  23703. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23704. for (row = 0; row <= precision.h; row++) {
  23705. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23706. for (col = 0; col <= precision.w; col++) {
  23707. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23708. position.y = 0;
  23709. positions.push(position.x, position.y, position.z);
  23710. normals.push(normal.x, normal.y, normal.z);
  23711. uvs.push(col / precision.w, row / precision.h);
  23712. }
  23713. }
  23714. }
  23715. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23716. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23717. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23718. }
  23719. }
  23720. // Result
  23721. var vertexData = new VertexData();
  23722. vertexData.indices = indices;
  23723. vertexData.positions = positions;
  23724. vertexData.normals = normals;
  23725. vertexData.uvs = uvs;
  23726. return vertexData;
  23727. };
  23728. VertexData.CreateGroundFromHeightMap = function (options) {
  23729. var indices = [];
  23730. var positions = [];
  23731. var normals = [];
  23732. var uvs = [];
  23733. var row, col;
  23734. // Vertices
  23735. for (row = 0; row <= options.subdivisions; row++) {
  23736. for (col = 0; col <= options.subdivisions; col++) {
  23737. 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));
  23738. // Compute height
  23739. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23740. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23741. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23742. var r = options.buffer[pos] / 255.0;
  23743. var g = options.buffer[pos + 1] / 255.0;
  23744. var b = options.buffer[pos + 2] / 255.0;
  23745. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23746. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23747. // Add vertex
  23748. positions.push(position.x, position.y, position.z);
  23749. normals.push(0, 0, 0);
  23750. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23751. }
  23752. }
  23753. // Indices
  23754. for (row = 0; row < options.subdivisions; row++) {
  23755. for (col = 0; col < options.subdivisions; col++) {
  23756. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23757. indices.push(col + 1 + row * (options.subdivisions + 1));
  23758. indices.push(col + row * (options.subdivisions + 1));
  23759. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23760. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23761. indices.push(col + row * (options.subdivisions + 1));
  23762. }
  23763. }
  23764. // Normals
  23765. VertexData.ComputeNormals(positions, indices, normals);
  23766. // Result
  23767. var vertexData = new VertexData();
  23768. vertexData.indices = indices;
  23769. vertexData.positions = positions;
  23770. vertexData.normals = normals;
  23771. vertexData.uvs = uvs;
  23772. return vertexData;
  23773. };
  23774. VertexData.CreatePlane = function (options) {
  23775. var indices = [];
  23776. var positions = [];
  23777. var normals = [];
  23778. var uvs = [];
  23779. var width = options.width || options.size || 1;
  23780. var height = options.height || options.size || 1;
  23781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23782. // Vertices
  23783. var halfWidth = width / 2.0;
  23784. var halfHeight = height / 2.0;
  23785. positions.push(-halfWidth, -halfHeight, 0);
  23786. normals.push(0, 0, -1.0);
  23787. uvs.push(0.0, 0.0);
  23788. positions.push(halfWidth, -halfHeight, 0);
  23789. normals.push(0, 0, -1.0);
  23790. uvs.push(1.0, 0.0);
  23791. positions.push(halfWidth, halfHeight, 0);
  23792. normals.push(0, 0, -1.0);
  23793. uvs.push(1.0, 1.0);
  23794. positions.push(-halfWidth, halfHeight, 0);
  23795. normals.push(0, 0, -1.0);
  23796. uvs.push(0.0, 1.0);
  23797. // Indices
  23798. indices.push(0);
  23799. indices.push(1);
  23800. indices.push(2);
  23801. indices.push(0);
  23802. indices.push(2);
  23803. indices.push(3);
  23804. // Sides
  23805. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23806. // Result
  23807. var vertexData = new VertexData();
  23808. vertexData.indices = indices;
  23809. vertexData.positions = positions;
  23810. vertexData.normals = normals;
  23811. vertexData.uvs = uvs;
  23812. return vertexData;
  23813. };
  23814. VertexData.CreateDisc = function (options) {
  23815. var positions = [];
  23816. var indices = [];
  23817. var normals = [];
  23818. var uvs = [];
  23819. var radius = options.radius || 0.5;
  23820. var tessellation = options.tessellation || 64;
  23821. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23823. // positions and uvs
  23824. positions.push(0, 0, 0); // disc center first
  23825. uvs.push(0.5, 0.5);
  23826. var theta = Math.PI * 2 * arc;
  23827. var step = theta / tessellation;
  23828. for (var a = 0; a < theta; a += step) {
  23829. var x = Math.cos(a);
  23830. var y = Math.sin(a);
  23831. var u = (x + 1) / 2;
  23832. var v = (1 - y) / 2;
  23833. positions.push(radius * x, radius * y, 0);
  23834. uvs.push(u, v);
  23835. }
  23836. if (arc === 1) {
  23837. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23838. uvs.push(uvs[2], uvs[3]);
  23839. }
  23840. //indices
  23841. var vertexNb = positions.length / 3;
  23842. for (var i = 1; i < vertexNb - 1; i++) {
  23843. indices.push(i + 1, 0, i);
  23844. }
  23845. // result
  23846. VertexData.ComputeNormals(positions, indices, normals);
  23847. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23848. var vertexData = new VertexData();
  23849. vertexData.indices = indices;
  23850. vertexData.positions = positions;
  23851. vertexData.normals = normals;
  23852. vertexData.uvs = uvs;
  23853. return vertexData;
  23854. };
  23855. VertexData.CreateIcoSphere = function (options) {
  23856. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23857. var radius = options.radius || 1;
  23858. var flat = options.flat || false;
  23859. var subdivisions = options.subdivisions || 1;
  23860. var t = (1 + Math.sqrt(5)) / 2;
  23861. // 12 vertex x,y,z
  23862. var ico_vertices = [
  23863. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23864. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23865. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23866. ];
  23867. // index of 3 vertex makes a face of icopshere
  23868. var ico_indices = [
  23869. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23870. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23871. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23872. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23873. ];
  23874. // uv as integer step (not pixels !)
  23875. var ico_vertexuv = [
  23876. 4, 1, 2, 1, 6, 3, 5, 4,
  23877. 4, 3, 3, 2, 7, 4, 3, 0,
  23878. 1, 0, 0, 1, 5, 0, 5, 2 // v8-11
  23879. ];
  23880. // Vertices [0, 1, ...9, A, B] : position on UV plane (7,8,9,10=A have duplicate position)
  23881. // v=5h 9+ 8+ 7+
  23882. // v=4h 9+ 3 6 A+
  23883. // v=3h 9+ 4 2 A+
  23884. // v=2h 9+ 5 B A+
  23885. // v=1h 9 1 0 A+
  23886. // v=0h 8 7 A
  23887. // u=0 1 2 3 4 5 6 7 8 9 *a
  23888. //
  23889. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23890. var ustep = 97 / 1024;
  23891. var vstep = 168 / 1024;
  23892. var uoffset = 50 / 1024;
  23893. var voffset = 51 / 1024;
  23894. var indices = [];
  23895. var positions = [];
  23896. var normals = [];
  23897. var uvs = [];
  23898. var current_indice = 0;
  23899. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23900. var face_vertex_pos = new Array(3);
  23901. var face_vertex_uv = new Array(3);
  23902. for (var v012 = 0; v012 < 3; v012++) {
  23903. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23904. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23905. }
  23906. // create all with normals
  23907. for (var face = 0; face < 20; face++) {
  23908. // 3 vertex per face
  23909. for (var v012 = 0; v012 < 3; v012++) {
  23910. // look up vertex 0,1,2 to its index in 0 to 11
  23911. var v_id = ico_indices[3 * face + v012];
  23912. // vertex have 3D position (x,y,z)
  23913. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * v_id], ico_vertices[3 * v_id + 1], ico_vertices[3 * v_id + 2]);
  23914. // Normalize to get normal, then scale to radius
  23915. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23916. // uv from vertex ID (may need fix due to unwrap on texture plan, unalias needed)
  23917. // vertex may get to different UV according to belonging face (see fix below)
  23918. var fix = 0;
  23919. // Vertice 9 UV to be fixed
  23920. if (face === 5 && v012 === 2) {
  23921. fix = 1;
  23922. }
  23923. if (face === 15 && v012 === 1) {
  23924. fix = 2;
  23925. }
  23926. if (face === 10 && v012 === 1) {
  23927. fix = 3;
  23928. }
  23929. if (face === 14 && v012 === 2) {
  23930. fix = 4;
  23931. }
  23932. // vertice 10 UV to be fixed
  23933. if (face === 4 && v012 === 1) {
  23934. fix = 1;
  23935. }
  23936. if (face === 7 && v012 === 1) {
  23937. fix = 2;
  23938. }
  23939. if (face === 17 && v012 === 2) {
  23940. fix = 3;
  23941. }
  23942. if (face === 8 && v012 === 0) {
  23943. fix = 4;
  23944. }
  23945. // vertice 7 UV to be fixed
  23946. if (face === 8 && v012 === 1) {
  23947. fix = 5;
  23948. }
  23949. if (face === 18 && v012 === 0) {
  23950. fix = 5;
  23951. }
  23952. // vertice 8 UV to be fixed
  23953. if (face === 13 && v012 === 2) {
  23954. fix = 5;
  23955. }
  23956. if (face === 14 && v012 === 1) {
  23957. fix = 5;
  23958. }
  23959. if (face === 18 && v012 === 2) {
  23960. fix = 5;
  23961. }
  23962. //
  23963. face_vertex_uv[v012].copyFromFloats((ico_vertexuv[2 * v_id] + fix) * ustep + uoffset, (ico_vertexuv[2 * v_id + 1] + fix) * vstep + voffset);
  23964. }
  23965. // Subdivide the face (interpolate pos, norm, uv)
  23966. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23967. // - norm is linear interpolation of vertex corner normal
  23968. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23969. // - uv is linear interpolation
  23970. //
  23971. // Topology is as below for sub-divide by 2
  23972. // vertex shown as v0,v1,v2
  23973. // interp index is i1 to progress in range [v0,v1[
  23974. // interp index is i2 to progress in range [v0,v2[
  23975. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23976. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23977. //
  23978. //
  23979. // i2 v2
  23980. // ^ ^
  23981. // / / \
  23982. // / / \
  23983. // / / \
  23984. // / / (0,1) \
  23985. // / #---------\
  23986. // / / \ (0,0)'/ \
  23987. // / / \ / \
  23988. // / / \ / \
  23989. // / / (0,0) \ / (1,0) \
  23990. // / #---------#---------\
  23991. // v0 v1
  23992. //
  23993. // --------------------> i1
  23994. //
  23995. // interp of (i1,i2):
  23996. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23997. // along i1 : lerp(x0,x1, i1/(S-i2))
  23998. //
  23999. // centroid of triangle is needed to get help normal computation
  24000. // (c1,c2) are used for centroid location
  24001. var interp_vertex = function (i1, i2, c1, c2) {
  24002. // vertex is interpolated from
  24003. // - face_vertex_pos[0..2]
  24004. // - face_vertex_uv[0..2]
  24005. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24006. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24007. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24008. pos_interp.normalize().scaleInPlace(radius);
  24009. var vertex_normal;
  24010. if (flat) {
  24011. // in flat mode, recalculate normal as face centroid normal
  24012. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24013. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24014. var centroid_interp = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24015. vertex_normal = BABYLON.Vector3.Normalize(centroid_interp);
  24016. }
  24017. else {
  24018. // in smooth mode, recalculate normal from each single vertex position
  24019. vertex_normal = BABYLON.Vector3.Normalize(pos_interp);
  24020. }
  24021. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24022. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24023. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24024. positions.push(pos_interp.x, pos_interp.y, pos_interp.z);
  24025. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24026. uvs.push(uv_interp.x, uv_interp.y);
  24027. // push each vertex has member of a face
  24028. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24029. indices.push(current_indice);
  24030. current_indice++;
  24031. };
  24032. for (var i2 = 0; i2 < subdivisions; i2++) {
  24033. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24034. // face : (i1,i2) for /\ :
  24035. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24036. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24037. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24038. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24039. if (i1 + i2 + 1 < subdivisions) {
  24040. // face : (i1,i2)' for \/ :
  24041. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24042. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24043. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24044. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24045. }
  24046. }
  24047. }
  24048. }
  24049. // Sides
  24050. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24051. // Result
  24052. var vertexData = new VertexData();
  24053. vertexData.indices = indices;
  24054. vertexData.positions = positions;
  24055. vertexData.normals = normals;
  24056. vertexData.uvs = uvs;
  24057. return vertexData;
  24058. };
  24059. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24060. VertexData.CreatePolyhedron = function (options) {
  24061. // provided polyhedron types :
  24062. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24063. // 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)
  24064. var polyhedra = [];
  24065. 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]] };
  24066. 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]] };
  24067. polyhedra[2] = {
  24068. 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]],
  24069. 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]]
  24070. };
  24071. polyhedra[3] = {
  24072. 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]],
  24073. 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]]
  24074. };
  24075. polyhedra[4] = {
  24076. 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]],
  24077. 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]]
  24078. };
  24079. 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]] };
  24080. 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]] };
  24081. 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]] };
  24082. 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]] };
  24083. 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]] };
  24084. 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]] };
  24085. 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]] };
  24086. 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]] };
  24087. 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]] };
  24088. polyhedra[14] = {
  24089. 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]],
  24090. 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]]
  24091. };
  24092. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24093. var size = options.size;
  24094. var sizeX = options.sizeX || size || 1;
  24095. var sizeY = options.sizeY || size || 1;
  24096. var sizeZ = options.sizeZ || size || 1;
  24097. var data = options.custom || polyhedra[type];
  24098. var nbfaces = data.face.length;
  24099. var faceUV = options.faceUV || new Array(nbfaces);
  24100. var faceColors = options.faceColors;
  24101. var singleFace = options.singleFace;
  24102. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24103. var positions = [];
  24104. var indices = [];
  24105. var normals = [];
  24106. var uvs = [];
  24107. var colors = [];
  24108. var index = 0;
  24109. var faceIdx = 0; // face cursor in the array "indexes"
  24110. var indexes = [];
  24111. var i = 0;
  24112. var f = 0;
  24113. var u, v, ang, x, y, tmp;
  24114. // default face colors and UV if undefined
  24115. if (!singleFace) {
  24116. for (f = 0; f < nbfaces; f++) {
  24117. if (faceColors && faceColors[f] === undefined) {
  24118. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24119. }
  24120. if (faceUV && faceUV[f] === undefined) {
  24121. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24122. }
  24123. }
  24124. }
  24125. if (singleFace) {
  24126. for (i = 0; i < data.vertex.length; i++) {
  24127. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24128. uvs.push(0, 0);
  24129. }
  24130. for (f = 0; f < nbfaces; f++) {
  24131. for (i = 0; i < data.face[f].length - 2; i++) {
  24132. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24133. }
  24134. }
  24135. }
  24136. else {
  24137. for (f = 0; f < nbfaces; f++) {
  24138. var fl = data.face[f].length; // number of vertices of the current face
  24139. ang = 2 * Math.PI / fl;
  24140. x = 0.5 * Math.tan(ang / 2);
  24141. y = 0.5;
  24142. // positions, uvs, colors
  24143. for (i = 0; i < fl; i++) {
  24144. // positions
  24145. 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);
  24146. indexes.push(index);
  24147. index++;
  24148. // uvs
  24149. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24150. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24151. uvs.push(u, v);
  24152. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24153. y = x * Math.sin(ang) + y * Math.cos(ang);
  24154. x = tmp;
  24155. // colors
  24156. if (faceColors) {
  24157. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24158. }
  24159. }
  24160. // indices from indexes
  24161. for (i = 0; i < fl - 2; i++) {
  24162. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24163. }
  24164. faceIdx += fl;
  24165. }
  24166. }
  24167. VertexData.ComputeNormals(positions, indices, normals);
  24168. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24169. var vertexData = new VertexData();
  24170. vertexData.positions = positions;
  24171. vertexData.indices = indices;
  24172. vertexData.normals = normals;
  24173. vertexData.uvs = uvs;
  24174. if (faceColors && !singleFace) {
  24175. vertexData.colors = colors;
  24176. }
  24177. return vertexData;
  24178. };
  24179. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24180. VertexData.CreateTorusKnot = function (options) {
  24181. var indices = [];
  24182. var positions = [];
  24183. var normals = [];
  24184. var uvs = [];
  24185. var radius = options.radius || 2;
  24186. var tube = options.tube || 0.5;
  24187. var radialSegments = options.radialSegments || 32;
  24188. var tubularSegments = options.tubularSegments || 32;
  24189. var p = options.p || 2;
  24190. var q = options.q || 3;
  24191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24192. // Helper
  24193. var getPos = function (angle) {
  24194. var cu = Math.cos(angle);
  24195. var su = Math.sin(angle);
  24196. var quOverP = q / p * angle;
  24197. var cs = Math.cos(quOverP);
  24198. var tx = radius * (2 + cs) * 0.5 * cu;
  24199. var ty = radius * (2 + cs) * su * 0.5;
  24200. var tz = radius * Math.sin(quOverP) * 0.5;
  24201. return new BABYLON.Vector3(tx, ty, tz);
  24202. };
  24203. // Vertices
  24204. var i;
  24205. var j;
  24206. for (i = 0; i <= radialSegments; i++) {
  24207. var modI = i % radialSegments;
  24208. var u = modI / radialSegments * 2 * p * Math.PI;
  24209. var p1 = getPos(u);
  24210. var p2 = getPos(u + 0.01);
  24211. var tang = p2.subtract(p1);
  24212. var n = p2.add(p1);
  24213. var bitan = BABYLON.Vector3.Cross(tang, n);
  24214. n = BABYLON.Vector3.Cross(bitan, tang);
  24215. bitan.normalize();
  24216. n.normalize();
  24217. for (j = 0; j < tubularSegments; j++) {
  24218. var modJ = j % tubularSegments;
  24219. var v = modJ / tubularSegments * 2 * Math.PI;
  24220. var cx = -tube * Math.cos(v);
  24221. var cy = tube * Math.sin(v);
  24222. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24223. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24224. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24225. uvs.push(i / radialSegments);
  24226. uvs.push(j / tubularSegments);
  24227. }
  24228. }
  24229. for (i = 0; i < radialSegments; i++) {
  24230. for (j = 0; j < tubularSegments; j++) {
  24231. var jNext = (j + 1) % tubularSegments;
  24232. var a = i * tubularSegments + j;
  24233. var b = (i + 1) * tubularSegments + j;
  24234. var c = (i + 1) * tubularSegments + jNext;
  24235. var d = i * tubularSegments + jNext;
  24236. indices.push(d);
  24237. indices.push(b);
  24238. indices.push(a);
  24239. indices.push(d);
  24240. indices.push(c);
  24241. indices.push(b);
  24242. }
  24243. }
  24244. // Normals
  24245. VertexData.ComputeNormals(positions, indices, normals);
  24246. // Sides
  24247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24248. // Result
  24249. var vertexData = new VertexData();
  24250. vertexData.indices = indices;
  24251. vertexData.positions = positions;
  24252. vertexData.normals = normals;
  24253. vertexData.uvs = uvs;
  24254. return vertexData;
  24255. };
  24256. // Tools
  24257. /**
  24258. * @param {any} - positions (number[] or Float32Array)
  24259. * @param {any} - indices (number[] or Uint16Array)
  24260. * @param {any} - normals (number[] or Float32Array)
  24261. */
  24262. VertexData.ComputeNormals = function (positions, indices, normals) {
  24263. var index = 0;
  24264. // temp Vector3
  24265. var p1p2 = BABYLON.Vector3.Zero();
  24266. var p3p2 = BABYLON.Vector3.Zero();
  24267. var faceNormal = BABYLON.Vector3.Zero();
  24268. var vertexNormali1 = BABYLON.Vector3.Zero();
  24269. for (index = 0; index < positions.length; index++) {
  24270. normals[index] = 0.0;
  24271. }
  24272. // indice triplet = 1 face
  24273. var nbFaces = indices.length / 3;
  24274. for (index = 0; index < nbFaces; index++) {
  24275. var i1 = indices[index * 3];
  24276. var i2 = indices[index * 3 + 1];
  24277. var i3 = indices[index * 3 + 2];
  24278. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24279. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24280. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24281. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24282. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24283. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24284. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24285. faceNormal.normalize();
  24286. normals[i1 * 3] += faceNormal.x;
  24287. normals[i1 * 3 + 1] += faceNormal.y;
  24288. normals[i1 * 3 + 2] += faceNormal.z;
  24289. normals[i2 * 3] += faceNormal.x;
  24290. normals[i2 * 3 + 1] += faceNormal.y;
  24291. normals[i2 * 3 + 2] += faceNormal.z;
  24292. normals[i3 * 3] += faceNormal.x;
  24293. normals[i3 * 3 + 1] += faceNormal.y;
  24294. normals[i3 * 3 + 2] += faceNormal.z;
  24295. }
  24296. // last normalization
  24297. for (index = 0; index < normals.length / 3; index++) {
  24298. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24299. vertexNormali1.normalize();
  24300. normals[index * 3] = vertexNormali1.x;
  24301. normals[index * 3 + 1] = vertexNormali1.y;
  24302. normals[index * 3 + 2] = vertexNormali1.z;
  24303. }
  24304. };
  24305. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24306. var li = indices.length;
  24307. var ln = normals.length;
  24308. var i;
  24309. var n;
  24310. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24311. switch (sideOrientation) {
  24312. case BABYLON.Mesh.FRONTSIDE:
  24313. // nothing changed
  24314. break;
  24315. case BABYLON.Mesh.BACKSIDE:
  24316. var tmp;
  24317. // indices
  24318. for (i = 0; i < li; i += 3) {
  24319. tmp = indices[i];
  24320. indices[i] = indices[i + 2];
  24321. indices[i + 2] = tmp;
  24322. }
  24323. // normals
  24324. for (n = 0; n < ln; n++) {
  24325. normals[n] = -normals[n];
  24326. }
  24327. break;
  24328. case BABYLON.Mesh.DOUBLESIDE:
  24329. // positions
  24330. var lp = positions.length;
  24331. var l = lp / 3;
  24332. for (var p = 0; p < lp; p++) {
  24333. positions[lp + p] = positions[p];
  24334. }
  24335. // indices
  24336. for (i = 0; i < li; i += 3) {
  24337. indices[i + li] = indices[i + 2] + l;
  24338. indices[i + 1 + li] = indices[i + 1] + l;
  24339. indices[i + 2 + li] = indices[i] + l;
  24340. }
  24341. // normals
  24342. for (n = 0; n < ln; n++) {
  24343. normals[ln + n] = -normals[n];
  24344. }
  24345. // uvs
  24346. var lu = uvs.length;
  24347. for (var u = 0; u < lu; u++) {
  24348. uvs[u + lu] = uvs[u];
  24349. }
  24350. break;
  24351. }
  24352. };
  24353. return VertexData;
  24354. })();
  24355. BABYLON.VertexData = VertexData;
  24356. })(BABYLON || (BABYLON = {}));
  24357. var BABYLON;
  24358. (function (BABYLON) {
  24359. var Tags = (function () {
  24360. function Tags() {
  24361. }
  24362. Tags.EnableFor = function (obj) {
  24363. obj._tags = obj._tags || {};
  24364. obj.hasTags = function () {
  24365. return Tags.HasTags(obj);
  24366. };
  24367. obj.addTags = function (tagsString) {
  24368. return Tags.AddTagsTo(obj, tagsString);
  24369. };
  24370. obj.removeTags = function (tagsString) {
  24371. return Tags.RemoveTagsFrom(obj, tagsString);
  24372. };
  24373. obj.matchesTagsQuery = function (tagsQuery) {
  24374. return Tags.MatchesQuery(obj, tagsQuery);
  24375. };
  24376. };
  24377. Tags.DisableFor = function (obj) {
  24378. delete obj._tags;
  24379. delete obj.hasTags;
  24380. delete obj.addTags;
  24381. delete obj.removeTags;
  24382. delete obj.matchesTagsQuery;
  24383. };
  24384. Tags.HasTags = function (obj) {
  24385. if (!obj._tags) {
  24386. return false;
  24387. }
  24388. return !BABYLON.Tools.IsEmpty(obj._tags);
  24389. };
  24390. Tags.GetTags = function (obj) {
  24391. if (!obj._tags) {
  24392. return null;
  24393. }
  24394. return obj._tags;
  24395. };
  24396. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24397. // a tag cannot start with '||', '&&', and '!'
  24398. // it cannot contain whitespaces
  24399. Tags.AddTagsTo = function (obj, tagsString) {
  24400. if (!tagsString) {
  24401. return;
  24402. }
  24403. if (typeof tagsString !== "string") {
  24404. return;
  24405. }
  24406. var tags = tagsString.split(" ");
  24407. for (var t in tags) {
  24408. Tags._AddTagTo(obj, tags[t]);
  24409. }
  24410. };
  24411. Tags._AddTagTo = function (obj, tag) {
  24412. tag = tag.trim();
  24413. if (tag === "" || tag === "true" || tag === "false") {
  24414. return;
  24415. }
  24416. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24417. return;
  24418. }
  24419. Tags.EnableFor(obj);
  24420. obj._tags[tag] = true;
  24421. };
  24422. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24423. if (!Tags.HasTags(obj)) {
  24424. return;
  24425. }
  24426. var tags = tagsString.split(" ");
  24427. for (var t in tags) {
  24428. Tags._RemoveTagFrom(obj, tags[t]);
  24429. }
  24430. };
  24431. Tags._RemoveTagFrom = function (obj, tag) {
  24432. delete obj._tags[tag];
  24433. };
  24434. Tags.MatchesQuery = function (obj, tagsQuery) {
  24435. if (tagsQuery === undefined) {
  24436. return true;
  24437. }
  24438. if (tagsQuery === "") {
  24439. return Tags.HasTags(obj);
  24440. }
  24441. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24442. };
  24443. return Tags;
  24444. })();
  24445. BABYLON.Tags = Tags;
  24446. })(BABYLON || (BABYLON = {}));
  24447. var BABYLON;
  24448. (function (BABYLON) {
  24449. var Internals;
  24450. (function (Internals) {
  24451. var AndOrNotEvaluator = (function () {
  24452. function AndOrNotEvaluator() {
  24453. }
  24454. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24455. if (!query.match(/\([^\(\)]*\)/g)) {
  24456. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24457. }
  24458. else {
  24459. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24460. // remove parenthesis
  24461. r = r.slice(1, r.length - 1);
  24462. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24463. });
  24464. }
  24465. if (query === "true") {
  24466. return true;
  24467. }
  24468. if (query === "false") {
  24469. return false;
  24470. }
  24471. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24472. };
  24473. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24474. evaluateCallback = evaluateCallback || (function (r) {
  24475. return r === "true" ? true : false;
  24476. });
  24477. var result;
  24478. var or = parenthesisContent.split("||");
  24479. for (var i in or) {
  24480. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24481. var and = ori.split("&&");
  24482. if (and.length > 1) {
  24483. for (var j = 0; j < and.length; ++j) {
  24484. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24485. if (andj !== "true" && andj !== "false") {
  24486. if (andj[0] === "!") {
  24487. result = !evaluateCallback(andj.substring(1));
  24488. }
  24489. else {
  24490. result = evaluateCallback(andj);
  24491. }
  24492. }
  24493. else {
  24494. result = andj === "true" ? true : false;
  24495. }
  24496. if (!result) {
  24497. ori = "false";
  24498. break;
  24499. }
  24500. }
  24501. }
  24502. if (result || ori === "true") {
  24503. result = true;
  24504. break;
  24505. }
  24506. // result equals false (or undefined)
  24507. if (ori !== "true" && ori !== "false") {
  24508. if (ori[0] === "!") {
  24509. result = !evaluateCallback(ori.substring(1));
  24510. }
  24511. else {
  24512. result = evaluateCallback(ori);
  24513. }
  24514. }
  24515. else {
  24516. result = ori === "true" ? true : false;
  24517. }
  24518. }
  24519. // the whole parenthesis scope is replaced by 'true' or 'false'
  24520. return result ? "true" : "false";
  24521. };
  24522. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24523. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24524. // remove whitespaces
  24525. r = r.replace(/[\s]/g, function () { return ""; });
  24526. return r.length % 2 ? "!" : "";
  24527. });
  24528. booleanString = booleanString.trim();
  24529. if (booleanString === "!true") {
  24530. booleanString = "false";
  24531. }
  24532. else if (booleanString === "!false") {
  24533. booleanString = "true";
  24534. }
  24535. return booleanString;
  24536. };
  24537. return AndOrNotEvaluator;
  24538. })();
  24539. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24540. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24541. })(BABYLON || (BABYLON = {}));
  24542. var BABYLON;
  24543. (function (BABYLON) {
  24544. var PostProcessRenderPass = (function () {
  24545. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24546. this._enabled = true;
  24547. this._refCount = 0;
  24548. this._name = name;
  24549. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24550. this.setRenderList(renderList);
  24551. this._renderTexture.onBeforeRender = beforeRender;
  24552. this._renderTexture.onAfterRender = afterRender;
  24553. this._scene = scene;
  24554. this._renderList = renderList;
  24555. }
  24556. // private
  24557. PostProcessRenderPass.prototype._incRefCount = function () {
  24558. if (this._refCount === 0) {
  24559. this._scene.customRenderTargets.push(this._renderTexture);
  24560. }
  24561. return ++this._refCount;
  24562. };
  24563. PostProcessRenderPass.prototype._decRefCount = function () {
  24564. this._refCount--;
  24565. if (this._refCount <= 0) {
  24566. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24567. }
  24568. return this._refCount;
  24569. };
  24570. PostProcessRenderPass.prototype._update = function () {
  24571. this.setRenderList(this._renderList);
  24572. };
  24573. // public
  24574. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24575. this._renderTexture.renderList = renderList;
  24576. };
  24577. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24578. return this._renderTexture;
  24579. };
  24580. return PostProcessRenderPass;
  24581. })();
  24582. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24583. })(BABYLON || (BABYLON = {}));
  24584. var BABYLON;
  24585. (function (BABYLON) {
  24586. var PostProcessRenderEffect = (function () {
  24587. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24588. this._engine = engine;
  24589. this._name = name;
  24590. this._singleInstance = singleInstance || true;
  24591. this._getPostProcess = getPostProcess;
  24592. this._cameras = [];
  24593. this._indicesForCamera = [];
  24594. this._postProcesses = {};
  24595. this._renderPasses = {};
  24596. this._renderEffectAsPasses = {};
  24597. }
  24598. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24599. get: function () {
  24600. for (var index in this._postProcesses) {
  24601. if (!this._postProcesses[index].isSupported) {
  24602. return false;
  24603. }
  24604. }
  24605. return true;
  24606. },
  24607. enumerable: true,
  24608. configurable: true
  24609. });
  24610. PostProcessRenderEffect.prototype._update = function () {
  24611. for (var renderPassName in this._renderPasses) {
  24612. this._renderPasses[renderPassName]._update();
  24613. }
  24614. };
  24615. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24616. this._renderPasses[renderPass._name] = renderPass;
  24617. this._linkParameters();
  24618. };
  24619. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24620. delete this._renderPasses[renderPass._name];
  24621. this._linkParameters();
  24622. };
  24623. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24624. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24625. this._linkParameters();
  24626. };
  24627. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24628. for (var renderPassName in this._renderPasses) {
  24629. if (renderPassName === passName) {
  24630. return this._renderPasses[passName];
  24631. }
  24632. }
  24633. };
  24634. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24635. this._renderPasses = {};
  24636. this._linkParameters();
  24637. };
  24638. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24639. var cameraKey;
  24640. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24641. for (var i = 0; i < _cam.length; i++) {
  24642. var camera = _cam[i];
  24643. var cameraName = camera.name;
  24644. if (this._singleInstance) {
  24645. cameraKey = 0;
  24646. }
  24647. else {
  24648. cameraKey = cameraName;
  24649. }
  24650. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24651. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24652. if (!this._indicesForCamera[cameraName]) {
  24653. this._indicesForCamera[cameraName] = [];
  24654. }
  24655. this._indicesForCamera[cameraName].push(index);
  24656. if (this._cameras.indexOf(camera) === -1) {
  24657. this._cameras[cameraName] = camera;
  24658. }
  24659. for (var passName in this._renderPasses) {
  24660. this._renderPasses[passName]._incRefCount();
  24661. }
  24662. }
  24663. this._linkParameters();
  24664. };
  24665. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24666. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24667. for (var i = 0; i < _cam.length; i++) {
  24668. var camera = _cam[i];
  24669. var cameraName = camera.name;
  24670. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24671. var index = this._cameras.indexOf(cameraName);
  24672. this._indicesForCamera.splice(index, 1);
  24673. this._cameras.splice(index, 1);
  24674. for (var passName in this._renderPasses) {
  24675. this._renderPasses[passName]._decRefCount();
  24676. }
  24677. }
  24678. };
  24679. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24680. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24681. for (var i = 0; i < _cam.length; i++) {
  24682. var camera = _cam[i];
  24683. var cameraName = camera.name;
  24684. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24685. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24686. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24687. }
  24688. }
  24689. for (var passName in this._renderPasses) {
  24690. this._renderPasses[passName]._incRefCount();
  24691. }
  24692. }
  24693. };
  24694. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24695. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24696. for (var i = 0; i < _cam.length; i++) {
  24697. var camera = _cam[i];
  24698. var cameraName = camera.Name;
  24699. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24700. for (var passName in this._renderPasses) {
  24701. this._renderPasses[passName]._decRefCount();
  24702. }
  24703. }
  24704. };
  24705. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24706. if (this._singleInstance) {
  24707. return this._postProcesses[0];
  24708. }
  24709. else {
  24710. return this._postProcesses[camera.name];
  24711. }
  24712. };
  24713. PostProcessRenderEffect.prototype._linkParameters = function () {
  24714. var _this = this;
  24715. for (var index in this._postProcesses) {
  24716. if (this.applyParameters) {
  24717. this.applyParameters(this._postProcesses[index]);
  24718. }
  24719. this._postProcesses[index].onBeforeRender = function (effect) {
  24720. _this._linkTextures(effect);
  24721. };
  24722. }
  24723. };
  24724. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24725. for (var renderPassName in this._renderPasses) {
  24726. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24727. }
  24728. for (var renderEffectName in this._renderEffectAsPasses) {
  24729. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24730. }
  24731. };
  24732. return PostProcessRenderEffect;
  24733. })();
  24734. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24735. })(BABYLON || (BABYLON = {}));
  24736. var BABYLON;
  24737. (function (BABYLON) {
  24738. var PostProcessRenderPipeline = (function () {
  24739. function PostProcessRenderPipeline(engine, name) {
  24740. this._engine = engine;
  24741. this._name = name;
  24742. this._renderEffects = {};
  24743. this._renderEffectsForIsolatedPass = {};
  24744. this._cameras = [];
  24745. }
  24746. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24747. get: function () {
  24748. for (var renderEffectName in this._renderEffects) {
  24749. if (!this._renderEffects[renderEffectName].isSupported) {
  24750. return false;
  24751. }
  24752. }
  24753. return true;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24759. this._renderEffects[renderEffect._name] = renderEffect;
  24760. };
  24761. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24762. var renderEffects = this._renderEffects[renderEffectName];
  24763. if (!renderEffects) {
  24764. return;
  24765. }
  24766. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24767. };
  24768. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24769. var renderEffects = this._renderEffects[renderEffectName];
  24770. if (!renderEffects) {
  24771. return;
  24772. }
  24773. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24774. };
  24775. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24776. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24777. var indicesToDelete = [];
  24778. var i;
  24779. for (i = 0; i < _cam.length; i++) {
  24780. var camera = _cam[i];
  24781. var cameraName = camera.name;
  24782. if (this._cameras.indexOf(camera) === -1) {
  24783. this._cameras[cameraName] = camera;
  24784. }
  24785. else if (unique) {
  24786. indicesToDelete.push(i);
  24787. }
  24788. }
  24789. for (i = 0; i < indicesToDelete.length; i++) {
  24790. cameras.splice(indicesToDelete[i], 1);
  24791. }
  24792. for (var renderEffectName in this._renderEffects) {
  24793. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24794. }
  24795. };
  24796. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24797. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24798. for (var renderEffectName in this._renderEffects) {
  24799. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24800. }
  24801. for (var i = 0; i < _cam.length; i++) {
  24802. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24803. }
  24804. };
  24805. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24806. var _this = this;
  24807. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24808. var pass = null;
  24809. var renderEffectName;
  24810. for (renderEffectName in this._renderEffects) {
  24811. pass = this._renderEffects[renderEffectName].getPass(passName);
  24812. if (pass != null) {
  24813. break;
  24814. }
  24815. }
  24816. if (pass === null) {
  24817. return;
  24818. }
  24819. for (renderEffectName in this._renderEffects) {
  24820. this._renderEffects[renderEffectName]._disable(_cam);
  24821. }
  24822. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24823. for (var i = 0; i < _cam.length; i++) {
  24824. var camera = _cam[i];
  24825. var cameraName = camera.name;
  24826. 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); });
  24827. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24828. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24829. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24830. }
  24831. };
  24832. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24833. var _this = this;
  24834. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24835. for (var i = 0; i < _cam.length; i++) {
  24836. var camera = _cam[i];
  24837. var cameraName = camera.name;
  24838. 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); });
  24839. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24840. }
  24841. for (var renderEffectName in this._renderEffects) {
  24842. this._renderEffects[renderEffectName]._enable(_cam);
  24843. }
  24844. };
  24845. PostProcessRenderPipeline.prototype._update = function () {
  24846. for (var renderEffectName in this._renderEffects) {
  24847. this._renderEffects[renderEffectName]._update();
  24848. }
  24849. for (var i = 0; i < this._cameras.length; i++) {
  24850. var cameraName = this._cameras[i].name;
  24851. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24852. this._renderEffectsForIsolatedPass[cameraName]._update();
  24853. }
  24854. }
  24855. };
  24856. PostProcessRenderPipeline.prototype.dispose = function () {
  24857. // Must be implemented by children
  24858. };
  24859. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24860. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24861. return PostProcessRenderPipeline;
  24862. })();
  24863. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24864. })(BABYLON || (BABYLON = {}));
  24865. var BABYLON;
  24866. (function (BABYLON) {
  24867. var PostProcessRenderPipelineManager = (function () {
  24868. function PostProcessRenderPipelineManager() {
  24869. this._renderPipelines = {};
  24870. }
  24871. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24872. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24873. };
  24874. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24875. var renderPipeline = this._renderPipelines[renderPipelineName];
  24876. if (!renderPipeline) {
  24877. return;
  24878. }
  24879. renderPipeline._attachCameras(cameras, unique);
  24880. };
  24881. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24882. var renderPipeline = this._renderPipelines[renderPipelineName];
  24883. if (!renderPipeline) {
  24884. return;
  24885. }
  24886. renderPipeline._detachCameras(cameras);
  24887. };
  24888. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24889. var renderPipeline = this._renderPipelines[renderPipelineName];
  24890. if (!renderPipeline) {
  24891. return;
  24892. }
  24893. renderPipeline._enableEffect(renderEffectName, cameras);
  24894. };
  24895. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24896. var renderPipeline = this._renderPipelines[renderPipelineName];
  24897. if (!renderPipeline) {
  24898. return;
  24899. }
  24900. renderPipeline._disableEffect(renderEffectName, cameras);
  24901. };
  24902. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24903. var renderPipeline = this._renderPipelines[renderPipelineName];
  24904. if (!renderPipeline) {
  24905. return;
  24906. }
  24907. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24908. };
  24909. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24910. var renderPipeline = this._renderPipelines[renderPipelineName];
  24911. if (!renderPipeline) {
  24912. return;
  24913. }
  24914. renderPipeline._disableDisplayOnlyPass(cameras);
  24915. };
  24916. PostProcessRenderPipelineManager.prototype.update = function () {
  24917. for (var renderPipelineName in this._renderPipelines) {
  24918. var pipeline = this._renderPipelines[renderPipelineName];
  24919. if (!pipeline.isSupported) {
  24920. pipeline.dispose();
  24921. delete this._renderPipelines[renderPipelineName];
  24922. }
  24923. else {
  24924. pipeline._update();
  24925. }
  24926. }
  24927. };
  24928. return PostProcessRenderPipelineManager;
  24929. })();
  24930. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24931. })(BABYLON || (BABYLON = {}));
  24932. var BABYLON;
  24933. (function (BABYLON) {
  24934. var BoundingBoxRenderer = (function () {
  24935. function BoundingBoxRenderer(scene) {
  24936. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24937. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24938. this.showBackLines = true;
  24939. this.renderList = new BABYLON.SmartArray(32);
  24940. this._scene = scene;
  24941. }
  24942. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24943. if (this._colorShader) {
  24944. return;
  24945. }
  24946. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24947. attributes: ["position"],
  24948. uniforms: ["worldViewProjection", "color"]
  24949. });
  24950. var engine = this._scene.getEngine();
  24951. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24952. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24953. 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]);
  24954. };
  24955. BoundingBoxRenderer.prototype.reset = function () {
  24956. this.renderList.reset();
  24957. };
  24958. BoundingBoxRenderer.prototype.render = function () {
  24959. if (this.renderList.length === 0) {
  24960. return;
  24961. }
  24962. this._prepareRessources();
  24963. if (!this._colorShader.isReady()) {
  24964. return;
  24965. }
  24966. var engine = this._scene.getEngine();
  24967. engine.setDepthWrite(false);
  24968. this._colorShader._preBind();
  24969. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24970. var boundingBox = this.renderList.data[boundingBoxIndex];
  24971. var min = boundingBox.minimum;
  24972. var max = boundingBox.maximum;
  24973. var diff = max.subtract(min);
  24974. var median = min.add(diff.scale(0.5));
  24975. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24976. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24977. .multiply(boundingBox.getWorldMatrix());
  24978. // VBOs
  24979. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24980. if (this.showBackLines) {
  24981. // Back
  24982. engine.setDepthFunctionToGreaterOrEqual();
  24983. this._scene.resetCachedMaterial();
  24984. this._colorShader.setColor4("color", this.backColor.toColor4());
  24985. this._colorShader.bind(worldMatrix);
  24986. // Draw order
  24987. engine.draw(false, 0, 24);
  24988. }
  24989. // Front
  24990. engine.setDepthFunctionToLess();
  24991. this._scene.resetCachedMaterial();
  24992. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24993. this._colorShader.bind(worldMatrix);
  24994. // Draw order
  24995. engine.draw(false, 0, 24);
  24996. }
  24997. this._colorShader.unbind();
  24998. engine.setDepthFunctionToLessOrEqual();
  24999. engine.setDepthWrite(true);
  25000. };
  25001. BoundingBoxRenderer.prototype.dispose = function () {
  25002. if (!this._colorShader) {
  25003. return;
  25004. }
  25005. this._colorShader.dispose();
  25006. this._vb.dispose();
  25007. this._scene.getEngine()._releaseBuffer(this._ib);
  25008. };
  25009. return BoundingBoxRenderer;
  25010. })();
  25011. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25012. })(BABYLON || (BABYLON = {}));
  25013. var BABYLON;
  25014. (function (BABYLON) {
  25015. var Condition = (function () {
  25016. function Condition(actionManager) {
  25017. this._actionManager = actionManager;
  25018. }
  25019. Condition.prototype.isValid = function () {
  25020. return true;
  25021. };
  25022. Condition.prototype._getProperty = function (propertyPath) {
  25023. return this._actionManager._getProperty(propertyPath);
  25024. };
  25025. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25026. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25027. };
  25028. return Condition;
  25029. })();
  25030. BABYLON.Condition = Condition;
  25031. var ValueCondition = (function (_super) {
  25032. __extends(ValueCondition, _super);
  25033. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25034. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25035. _super.call(this, actionManager);
  25036. this.propertyPath = propertyPath;
  25037. this.value = value;
  25038. this.operator = operator;
  25039. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25040. this._property = this._getProperty(this.propertyPath);
  25041. }
  25042. Object.defineProperty(ValueCondition, "IsEqual", {
  25043. get: function () {
  25044. return ValueCondition._IsEqual;
  25045. },
  25046. enumerable: true,
  25047. configurable: true
  25048. });
  25049. Object.defineProperty(ValueCondition, "IsDifferent", {
  25050. get: function () {
  25051. return ValueCondition._IsDifferent;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. Object.defineProperty(ValueCondition, "IsGreater", {
  25057. get: function () {
  25058. return ValueCondition._IsGreater;
  25059. },
  25060. enumerable: true,
  25061. configurable: true
  25062. });
  25063. Object.defineProperty(ValueCondition, "IsLesser", {
  25064. get: function () {
  25065. return ValueCondition._IsLesser;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. // Methods
  25071. ValueCondition.prototype.isValid = function () {
  25072. switch (this.operator) {
  25073. case ValueCondition.IsGreater:
  25074. return this._target[this._property] > this.value;
  25075. case ValueCondition.IsLesser:
  25076. return this._target[this._property] < this.value;
  25077. case ValueCondition.IsEqual:
  25078. case ValueCondition.IsDifferent:
  25079. var check;
  25080. if (this.value.equals) {
  25081. check = this.value.equals(this._target[this._property]);
  25082. }
  25083. else {
  25084. check = this.value === this._target[this._property];
  25085. }
  25086. return this.operator === ValueCondition.IsEqual ? check : !check;
  25087. }
  25088. return false;
  25089. };
  25090. // Statics
  25091. ValueCondition._IsEqual = 0;
  25092. ValueCondition._IsDifferent = 1;
  25093. ValueCondition._IsGreater = 2;
  25094. ValueCondition._IsLesser = 3;
  25095. return ValueCondition;
  25096. })(Condition);
  25097. BABYLON.ValueCondition = ValueCondition;
  25098. var PredicateCondition = (function (_super) {
  25099. __extends(PredicateCondition, _super);
  25100. function PredicateCondition(actionManager, predicate) {
  25101. _super.call(this, actionManager);
  25102. this.predicate = predicate;
  25103. }
  25104. PredicateCondition.prototype.isValid = function () {
  25105. return this.predicate();
  25106. };
  25107. return PredicateCondition;
  25108. })(Condition);
  25109. BABYLON.PredicateCondition = PredicateCondition;
  25110. var StateCondition = (function (_super) {
  25111. __extends(StateCondition, _super);
  25112. function StateCondition(actionManager, target, value) {
  25113. _super.call(this, actionManager);
  25114. this.value = value;
  25115. this._target = target;
  25116. }
  25117. // Methods
  25118. StateCondition.prototype.isValid = function () {
  25119. return this._target.state === this.value;
  25120. };
  25121. return StateCondition;
  25122. })(Condition);
  25123. BABYLON.StateCondition = StateCondition;
  25124. })(BABYLON || (BABYLON = {}));
  25125. var BABYLON;
  25126. (function (BABYLON) {
  25127. var Action = (function () {
  25128. function Action(triggerOptions, condition) {
  25129. this.triggerOptions = triggerOptions;
  25130. if (triggerOptions.parameter) {
  25131. this.trigger = triggerOptions.trigger;
  25132. this._triggerParameter = triggerOptions.parameter;
  25133. }
  25134. else {
  25135. this.trigger = triggerOptions;
  25136. }
  25137. this._nextActiveAction = this;
  25138. this._condition = condition;
  25139. }
  25140. // Methods
  25141. Action.prototype._prepare = function () {
  25142. };
  25143. Action.prototype.getTriggerParameter = function () {
  25144. return this._triggerParameter;
  25145. };
  25146. Action.prototype._executeCurrent = function (evt) {
  25147. if (this._nextActiveAction._condition) {
  25148. var condition = this._nextActiveAction._condition;
  25149. var currentRenderId = this._actionManager.getScene().getRenderId();
  25150. // We cache the current evaluation for the current frame
  25151. if (condition._evaluationId === currentRenderId) {
  25152. if (!condition._currentResult) {
  25153. return;
  25154. }
  25155. }
  25156. else {
  25157. condition._evaluationId = currentRenderId;
  25158. if (!condition.isValid()) {
  25159. condition._currentResult = false;
  25160. return;
  25161. }
  25162. condition._currentResult = true;
  25163. }
  25164. }
  25165. this._nextActiveAction.execute(evt);
  25166. if (this._nextActiveAction._child) {
  25167. if (!this._nextActiveAction._child._actionManager) {
  25168. this._nextActiveAction._child._actionManager = this._actionManager;
  25169. }
  25170. this._nextActiveAction = this._nextActiveAction._child;
  25171. }
  25172. else {
  25173. this._nextActiveAction = this;
  25174. }
  25175. };
  25176. Action.prototype.execute = function (evt) {
  25177. };
  25178. Action.prototype.then = function (action) {
  25179. this._child = action;
  25180. action._actionManager = this._actionManager;
  25181. action._prepare();
  25182. return action;
  25183. };
  25184. Action.prototype._getProperty = function (propertyPath) {
  25185. return this._actionManager._getProperty(propertyPath);
  25186. };
  25187. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25188. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25189. };
  25190. return Action;
  25191. })();
  25192. BABYLON.Action = Action;
  25193. })(BABYLON || (BABYLON = {}));
  25194. var BABYLON;
  25195. (function (BABYLON) {
  25196. /**
  25197. * ActionEvent is the event beint sent when an action is triggered.
  25198. */
  25199. var ActionEvent = (function () {
  25200. /**
  25201. * @constructor
  25202. * @param source The mesh or sprite that triggered the action.
  25203. * @param pointerX The X mouse cursor position at the time of the event
  25204. * @param pointerY The Y mouse cursor position at the time of the event
  25205. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25206. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25207. */
  25208. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25209. this.source = source;
  25210. this.pointerX = pointerX;
  25211. this.pointerY = pointerY;
  25212. this.meshUnderPointer = meshUnderPointer;
  25213. this.sourceEvent = sourceEvent;
  25214. this.additionalData = additionalData;
  25215. }
  25216. /**
  25217. * Helper function to auto-create an ActionEvent from a source mesh.
  25218. * @param source The source mesh that triggered the event
  25219. * @param evt {Event} The original (browser) event
  25220. */
  25221. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25222. var scene = source.getScene();
  25223. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25224. };
  25225. /**
  25226. * Helper function to auto-create an ActionEvent from a source mesh.
  25227. * @param source The source sprite that triggered the event
  25228. * @param scene Scene associated with the sprite
  25229. * @param evt {Event} The original (browser) event
  25230. */
  25231. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25232. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25233. };
  25234. /**
  25235. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25236. * @param scene the scene where the event occurred
  25237. * @param evt {Event} The original (browser) event
  25238. */
  25239. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25240. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25241. };
  25242. return ActionEvent;
  25243. })();
  25244. BABYLON.ActionEvent = ActionEvent;
  25245. /**
  25246. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25247. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25248. */
  25249. var ActionManager = (function () {
  25250. function ActionManager(scene) {
  25251. // Members
  25252. this.actions = new Array();
  25253. this._scene = scene;
  25254. scene._actionManagers.push(this);
  25255. }
  25256. Object.defineProperty(ActionManager, "NothingTrigger", {
  25257. get: function () {
  25258. return ActionManager._NothingTrigger;
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25264. get: function () {
  25265. return ActionManager._OnPickTrigger;
  25266. },
  25267. enumerable: true,
  25268. configurable: true
  25269. });
  25270. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25271. get: function () {
  25272. return ActionManager._OnLeftPickTrigger;
  25273. },
  25274. enumerable: true,
  25275. configurable: true
  25276. });
  25277. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25278. get: function () {
  25279. return ActionManager._OnRightPickTrigger;
  25280. },
  25281. enumerable: true,
  25282. configurable: true
  25283. });
  25284. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25285. get: function () {
  25286. return ActionManager._OnCenterPickTrigger;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25292. get: function () {
  25293. return ActionManager._OnPointerOverTrigger;
  25294. },
  25295. enumerable: true,
  25296. configurable: true
  25297. });
  25298. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25299. get: function () {
  25300. return ActionManager._OnPointerOutTrigger;
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25306. get: function () {
  25307. return ActionManager._OnEveryFrameTrigger;
  25308. },
  25309. enumerable: true,
  25310. configurable: true
  25311. });
  25312. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25313. get: function () {
  25314. return ActionManager._OnIntersectionEnterTrigger;
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25320. get: function () {
  25321. return ActionManager._OnIntersectionExitTrigger;
  25322. },
  25323. enumerable: true,
  25324. configurable: true
  25325. });
  25326. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25327. get: function () {
  25328. return ActionManager._OnKeyDownTrigger;
  25329. },
  25330. enumerable: true,
  25331. configurable: true
  25332. });
  25333. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25334. get: function () {
  25335. return ActionManager._OnKeyUpTrigger;
  25336. },
  25337. enumerable: true,
  25338. configurable: true
  25339. });
  25340. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25341. get: function () {
  25342. return ActionManager._OnPickUpTrigger;
  25343. },
  25344. enumerable: true,
  25345. configurable: true
  25346. });
  25347. // Methods
  25348. ActionManager.prototype.dispose = function () {
  25349. var index = this._scene._actionManagers.indexOf(this);
  25350. if (index > -1) {
  25351. this._scene._actionManagers.splice(index, 1);
  25352. }
  25353. };
  25354. ActionManager.prototype.getScene = function () {
  25355. return this._scene;
  25356. };
  25357. /**
  25358. * Does this action manager handles actions of any of the given triggers
  25359. * @param {number[]} triggers - the triggers to be tested
  25360. * @return {boolean} whether one (or more) of the triggers is handeled
  25361. */
  25362. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25363. for (var index = 0; index < this.actions.length; index++) {
  25364. var action = this.actions[index];
  25365. if (triggers.indexOf(action.trigger) > -1) {
  25366. return true;
  25367. }
  25368. }
  25369. return false;
  25370. };
  25371. /**
  25372. * Does this action manager handles actions of a given trigger
  25373. * @param {number} trigger - the trigger to be tested
  25374. * @return {boolean} whether the trigger is handeled
  25375. */
  25376. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25377. for (var index = 0; index < this.actions.length; index++) {
  25378. var action = this.actions[index];
  25379. if (action.trigger === trigger) {
  25380. return true;
  25381. }
  25382. }
  25383. return false;
  25384. };
  25385. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25386. /**
  25387. * Does this action manager has pointer triggers
  25388. * @return {boolean} whether or not it has pointer triggers
  25389. */
  25390. get: function () {
  25391. for (var index = 0; index < this.actions.length; index++) {
  25392. var action = this.actions[index];
  25393. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25394. return true;
  25395. }
  25396. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25397. return true;
  25398. }
  25399. }
  25400. return false;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25406. /**
  25407. * Does this action manager has pick triggers
  25408. * @return {boolean} whether or not it has pick triggers
  25409. */
  25410. get: function () {
  25411. for (var index = 0; index < this.actions.length; index++) {
  25412. var action = this.actions[index];
  25413. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25414. return true;
  25415. }
  25416. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25417. return true;
  25418. }
  25419. }
  25420. return false;
  25421. },
  25422. enumerable: true,
  25423. configurable: true
  25424. });
  25425. /**
  25426. * Registers an action to this action manager
  25427. * @param {BABYLON.Action} action - the action to be registered
  25428. * @return {BABYLON.Action} the action amended (prepared) after registration
  25429. */
  25430. ActionManager.prototype.registerAction = function (action) {
  25431. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25432. if (this.getScene().actionManager !== this) {
  25433. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25434. return null;
  25435. }
  25436. }
  25437. this.actions.push(action);
  25438. action._actionManager = this;
  25439. action._prepare();
  25440. return action;
  25441. };
  25442. /**
  25443. * Process a specific trigger
  25444. * @param {number} trigger - the trigger to process
  25445. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25446. */
  25447. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25448. for (var index = 0; index < this.actions.length; index++) {
  25449. var action = this.actions[index];
  25450. if (action.trigger === trigger) {
  25451. if (trigger === ActionManager.OnKeyUpTrigger
  25452. || trigger === ActionManager.OnKeyDownTrigger) {
  25453. var parameter = action.getTriggerParameter();
  25454. if (parameter) {
  25455. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25456. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25457. if (actualkey !== parameter.toLowerCase()) {
  25458. continue;
  25459. }
  25460. }
  25461. }
  25462. action._executeCurrent(evt);
  25463. }
  25464. }
  25465. };
  25466. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25467. var properties = propertyPath.split(".");
  25468. for (var index = 0; index < properties.length - 1; index++) {
  25469. target = target[properties[index]];
  25470. }
  25471. return target;
  25472. };
  25473. ActionManager.prototype._getProperty = function (propertyPath) {
  25474. var properties = propertyPath.split(".");
  25475. return properties[properties.length - 1];
  25476. };
  25477. // Statics
  25478. ActionManager._NothingTrigger = 0;
  25479. ActionManager._OnPickTrigger = 1;
  25480. ActionManager._OnLeftPickTrigger = 2;
  25481. ActionManager._OnRightPickTrigger = 3;
  25482. ActionManager._OnCenterPickTrigger = 4;
  25483. ActionManager._OnPointerOverTrigger = 5;
  25484. ActionManager._OnPointerOutTrigger = 6;
  25485. ActionManager._OnEveryFrameTrigger = 7;
  25486. ActionManager._OnIntersectionEnterTrigger = 8;
  25487. ActionManager._OnIntersectionExitTrigger = 9;
  25488. ActionManager._OnKeyDownTrigger = 10;
  25489. ActionManager._OnKeyUpTrigger = 11;
  25490. ActionManager._OnPickUpTrigger = 12;
  25491. return ActionManager;
  25492. })();
  25493. BABYLON.ActionManager = ActionManager;
  25494. })(BABYLON || (BABYLON = {}));
  25495. var BABYLON;
  25496. (function (BABYLON) {
  25497. var InterpolateValueAction = (function (_super) {
  25498. __extends(InterpolateValueAction, _super);
  25499. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25500. if (duration === void 0) { duration = 1000; }
  25501. _super.call(this, triggerOptions, condition);
  25502. this.propertyPath = propertyPath;
  25503. this.value = value;
  25504. this.duration = duration;
  25505. this.stopOtherAnimations = stopOtherAnimations;
  25506. this.onInterpolationDone = onInterpolationDone;
  25507. this._target = target;
  25508. }
  25509. InterpolateValueAction.prototype._prepare = function () {
  25510. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25511. this._property = this._getProperty(this.propertyPath);
  25512. };
  25513. InterpolateValueAction.prototype.execute = function () {
  25514. var scene = this._actionManager.getScene();
  25515. var keys = [
  25516. {
  25517. frame: 0,
  25518. value: this._target[this._property]
  25519. }, {
  25520. frame: 100,
  25521. value: this.value
  25522. }
  25523. ];
  25524. var dataType;
  25525. if (typeof this.value === "number") {
  25526. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25527. }
  25528. else if (this.value instanceof BABYLON.Color3) {
  25529. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25530. }
  25531. else if (this.value instanceof BABYLON.Vector3) {
  25532. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25533. }
  25534. else if (this.value instanceof BABYLON.Matrix) {
  25535. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25536. }
  25537. else if (this.value instanceof BABYLON.Quaternion) {
  25538. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25539. }
  25540. else {
  25541. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25542. return;
  25543. }
  25544. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25545. animation.setKeys(keys);
  25546. if (this.stopOtherAnimations) {
  25547. scene.stopAnimation(this._target);
  25548. }
  25549. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25550. };
  25551. return InterpolateValueAction;
  25552. })(BABYLON.Action);
  25553. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25554. })(BABYLON || (BABYLON = {}));
  25555. var BABYLON;
  25556. (function (BABYLON) {
  25557. var SwitchBooleanAction = (function (_super) {
  25558. __extends(SwitchBooleanAction, _super);
  25559. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25560. _super.call(this, triggerOptions, condition);
  25561. this.propertyPath = propertyPath;
  25562. this._target = target;
  25563. }
  25564. SwitchBooleanAction.prototype._prepare = function () {
  25565. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25566. this._property = this._getProperty(this.propertyPath);
  25567. };
  25568. SwitchBooleanAction.prototype.execute = function () {
  25569. this._target[this._property] = !this._target[this._property];
  25570. };
  25571. return SwitchBooleanAction;
  25572. })(BABYLON.Action);
  25573. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25574. var SetStateAction = (function (_super) {
  25575. __extends(SetStateAction, _super);
  25576. function SetStateAction(triggerOptions, target, value, condition) {
  25577. _super.call(this, triggerOptions, condition);
  25578. this.value = value;
  25579. this._target = target;
  25580. }
  25581. SetStateAction.prototype.execute = function () {
  25582. this._target.state = this.value;
  25583. };
  25584. return SetStateAction;
  25585. })(BABYLON.Action);
  25586. BABYLON.SetStateAction = SetStateAction;
  25587. var SetValueAction = (function (_super) {
  25588. __extends(SetValueAction, _super);
  25589. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25590. _super.call(this, triggerOptions, condition);
  25591. this.propertyPath = propertyPath;
  25592. this.value = value;
  25593. this._target = target;
  25594. }
  25595. SetValueAction.prototype._prepare = function () {
  25596. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25597. this._property = this._getProperty(this.propertyPath);
  25598. };
  25599. SetValueAction.prototype.execute = function () {
  25600. this._target[this._property] = this.value;
  25601. };
  25602. return SetValueAction;
  25603. })(BABYLON.Action);
  25604. BABYLON.SetValueAction = SetValueAction;
  25605. var IncrementValueAction = (function (_super) {
  25606. __extends(IncrementValueAction, _super);
  25607. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25608. _super.call(this, triggerOptions, condition);
  25609. this.propertyPath = propertyPath;
  25610. this.value = value;
  25611. this._target = target;
  25612. }
  25613. IncrementValueAction.prototype._prepare = function () {
  25614. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25615. this._property = this._getProperty(this.propertyPath);
  25616. if (typeof this._target[this._property] !== "number") {
  25617. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25618. }
  25619. };
  25620. IncrementValueAction.prototype.execute = function () {
  25621. this._target[this._property] += this.value;
  25622. };
  25623. return IncrementValueAction;
  25624. })(BABYLON.Action);
  25625. BABYLON.IncrementValueAction = IncrementValueAction;
  25626. var PlayAnimationAction = (function (_super) {
  25627. __extends(PlayAnimationAction, _super);
  25628. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25629. _super.call(this, triggerOptions, condition);
  25630. this.from = from;
  25631. this.to = to;
  25632. this.loop = loop;
  25633. this._target = target;
  25634. }
  25635. PlayAnimationAction.prototype._prepare = function () {
  25636. };
  25637. PlayAnimationAction.prototype.execute = function () {
  25638. var scene = this._actionManager.getScene();
  25639. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25640. };
  25641. return PlayAnimationAction;
  25642. })(BABYLON.Action);
  25643. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25644. var StopAnimationAction = (function (_super) {
  25645. __extends(StopAnimationAction, _super);
  25646. function StopAnimationAction(triggerOptions, target, condition) {
  25647. _super.call(this, triggerOptions, condition);
  25648. this._target = target;
  25649. }
  25650. StopAnimationAction.prototype._prepare = function () {
  25651. };
  25652. StopAnimationAction.prototype.execute = function () {
  25653. var scene = this._actionManager.getScene();
  25654. scene.stopAnimation(this._target);
  25655. };
  25656. return StopAnimationAction;
  25657. })(BABYLON.Action);
  25658. BABYLON.StopAnimationAction = StopAnimationAction;
  25659. var DoNothingAction = (function (_super) {
  25660. __extends(DoNothingAction, _super);
  25661. function DoNothingAction(triggerOptions, condition) {
  25662. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25663. _super.call(this, triggerOptions, condition);
  25664. }
  25665. DoNothingAction.prototype.execute = function () {
  25666. };
  25667. return DoNothingAction;
  25668. })(BABYLON.Action);
  25669. BABYLON.DoNothingAction = DoNothingAction;
  25670. var CombineAction = (function (_super) {
  25671. __extends(CombineAction, _super);
  25672. function CombineAction(triggerOptions, children, condition) {
  25673. _super.call(this, triggerOptions, condition);
  25674. this.children = children;
  25675. }
  25676. CombineAction.prototype._prepare = function () {
  25677. for (var index = 0; index < this.children.length; index++) {
  25678. this.children[index]._actionManager = this._actionManager;
  25679. this.children[index]._prepare();
  25680. }
  25681. };
  25682. CombineAction.prototype.execute = function (evt) {
  25683. for (var index = 0; index < this.children.length; index++) {
  25684. this.children[index].execute(evt);
  25685. }
  25686. };
  25687. return CombineAction;
  25688. })(BABYLON.Action);
  25689. BABYLON.CombineAction = CombineAction;
  25690. var ExecuteCodeAction = (function (_super) {
  25691. __extends(ExecuteCodeAction, _super);
  25692. function ExecuteCodeAction(triggerOptions, func, condition) {
  25693. _super.call(this, triggerOptions, condition);
  25694. this.func = func;
  25695. }
  25696. ExecuteCodeAction.prototype.execute = function (evt) {
  25697. this.func(evt);
  25698. };
  25699. return ExecuteCodeAction;
  25700. })(BABYLON.Action);
  25701. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25702. var SetParentAction = (function (_super) {
  25703. __extends(SetParentAction, _super);
  25704. function SetParentAction(triggerOptions, target, parent, condition) {
  25705. _super.call(this, triggerOptions, condition);
  25706. this._target = target;
  25707. this._parent = parent;
  25708. }
  25709. SetParentAction.prototype._prepare = function () {
  25710. };
  25711. SetParentAction.prototype.execute = function () {
  25712. if (this._target.parent === this._parent) {
  25713. return;
  25714. }
  25715. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25716. invertParentWorldMatrix.invert();
  25717. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25718. this._target.parent = this._parent;
  25719. };
  25720. return SetParentAction;
  25721. })(BABYLON.Action);
  25722. BABYLON.SetParentAction = SetParentAction;
  25723. var PlaySoundAction = (function (_super) {
  25724. __extends(PlaySoundAction, _super);
  25725. function PlaySoundAction(triggerOptions, sound, condition) {
  25726. _super.call(this, triggerOptions, condition);
  25727. this._sound = sound;
  25728. }
  25729. PlaySoundAction.prototype._prepare = function () {
  25730. };
  25731. PlaySoundAction.prototype.execute = function () {
  25732. if (this._sound !== undefined)
  25733. this._sound.play();
  25734. };
  25735. return PlaySoundAction;
  25736. })(BABYLON.Action);
  25737. BABYLON.PlaySoundAction = PlaySoundAction;
  25738. var StopSoundAction = (function (_super) {
  25739. __extends(StopSoundAction, _super);
  25740. function StopSoundAction(triggerOptions, sound, condition) {
  25741. _super.call(this, triggerOptions, condition);
  25742. this._sound = sound;
  25743. }
  25744. StopSoundAction.prototype._prepare = function () {
  25745. };
  25746. StopSoundAction.prototype.execute = function () {
  25747. if (this._sound !== undefined)
  25748. this._sound.stop();
  25749. };
  25750. return StopSoundAction;
  25751. })(BABYLON.Action);
  25752. BABYLON.StopSoundAction = StopSoundAction;
  25753. })(BABYLON || (BABYLON = {}));
  25754. var BABYLON;
  25755. (function (BABYLON) {
  25756. var Geometry = (function () {
  25757. function Geometry(id, scene, vertexData, updatable, mesh) {
  25758. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25759. this._totalVertices = 0;
  25760. this._isDisposed = false;
  25761. this.id = id;
  25762. this._engine = scene.getEngine();
  25763. this._meshes = [];
  25764. this._scene = scene;
  25765. //Init vertex buffer cache
  25766. this._vertexBuffers = {};
  25767. this._indices = [];
  25768. // vertexData
  25769. if (vertexData) {
  25770. this.setAllVerticesData(vertexData, updatable);
  25771. }
  25772. else {
  25773. this._totalVertices = 0;
  25774. this._indices = [];
  25775. }
  25776. // applyToMesh
  25777. if (mesh) {
  25778. this.applyToMesh(mesh);
  25779. mesh.computeWorldMatrix(true);
  25780. }
  25781. }
  25782. Object.defineProperty(Geometry.prototype, "extend", {
  25783. get: function () {
  25784. return this._extend;
  25785. },
  25786. enumerable: true,
  25787. configurable: true
  25788. });
  25789. Geometry.prototype.getScene = function () {
  25790. return this._scene;
  25791. };
  25792. Geometry.prototype.getEngine = function () {
  25793. return this._engine;
  25794. };
  25795. Geometry.prototype.isReady = function () {
  25796. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25797. };
  25798. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25799. vertexData.applyToGeometry(this, updatable);
  25800. this.notifyUpdate();
  25801. };
  25802. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25803. if (this._vertexBuffers[kind]) {
  25804. this._vertexBuffers[kind].dispose();
  25805. }
  25806. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25807. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25808. stride = this._vertexBuffers[kind].getStrideSize();
  25809. this._totalVertices = data.length / stride;
  25810. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25811. var meshes = this._meshes;
  25812. var numOfMeshes = meshes.length;
  25813. for (var index = 0; index < numOfMeshes; index++) {
  25814. var mesh = meshes[index];
  25815. mesh._resetPointsArrayCache();
  25816. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25817. mesh._createGlobalSubMesh();
  25818. mesh.computeWorldMatrix(true);
  25819. }
  25820. }
  25821. this.notifyUpdate(kind);
  25822. };
  25823. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25824. var vertexBuffer = this.getVertexBuffer(kind);
  25825. if (!vertexBuffer) {
  25826. return;
  25827. }
  25828. vertexBuffer.updateDirectly(data, offset);
  25829. this.notifyUpdate(kind);
  25830. };
  25831. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25832. var vertexBuffer = this.getVertexBuffer(kind);
  25833. if (!vertexBuffer) {
  25834. return;
  25835. }
  25836. vertexBuffer.update(data);
  25837. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25838. var stride = vertexBuffer.getStrideSize();
  25839. this._totalVertices = data.length / stride;
  25840. if (updateExtends) {
  25841. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25842. }
  25843. var meshes = this._meshes;
  25844. var numOfMeshes = meshes.length;
  25845. for (var index = 0; index < numOfMeshes; index++) {
  25846. var mesh = meshes[index];
  25847. mesh._resetPointsArrayCache();
  25848. if (updateExtends) {
  25849. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25850. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25851. var subMesh = mesh.subMeshes[subIndex];
  25852. subMesh.refreshBoundingInfo();
  25853. }
  25854. }
  25855. }
  25856. }
  25857. this.notifyUpdate(kind);
  25858. };
  25859. Geometry.prototype.getTotalVertices = function () {
  25860. if (!this.isReady()) {
  25861. return 0;
  25862. }
  25863. return this._totalVertices;
  25864. };
  25865. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25866. var vertexBuffer = this.getVertexBuffer(kind);
  25867. if (!vertexBuffer) {
  25868. return null;
  25869. }
  25870. var orig = vertexBuffer.getData();
  25871. if (!copyWhenShared || this._meshes.length === 1) {
  25872. return orig;
  25873. }
  25874. else {
  25875. var len = orig.length;
  25876. var copy = [];
  25877. for (var i = 0; i < len; i++) {
  25878. copy.push(orig[i]);
  25879. }
  25880. return copy;
  25881. }
  25882. };
  25883. Geometry.prototype.getVertexBuffer = function (kind) {
  25884. if (!this.isReady()) {
  25885. return null;
  25886. }
  25887. return this._vertexBuffers[kind];
  25888. };
  25889. Geometry.prototype.getVertexBuffers = function () {
  25890. if (!this.isReady()) {
  25891. return null;
  25892. }
  25893. return this._vertexBuffers;
  25894. };
  25895. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25896. if (!this._vertexBuffers) {
  25897. if (this._delayInfo) {
  25898. return this._delayInfo.indexOf(kind) !== -1;
  25899. }
  25900. return false;
  25901. }
  25902. return this._vertexBuffers[kind] !== undefined;
  25903. };
  25904. Geometry.prototype.getVerticesDataKinds = function () {
  25905. var result = [];
  25906. var kind;
  25907. if (!this._vertexBuffers && this._delayInfo) {
  25908. for (kind in this._delayInfo) {
  25909. result.push(kind);
  25910. }
  25911. }
  25912. else {
  25913. for (kind in this._vertexBuffers) {
  25914. result.push(kind);
  25915. }
  25916. }
  25917. return result;
  25918. };
  25919. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25920. if (this._indexBuffer) {
  25921. this._engine._releaseBuffer(this._indexBuffer);
  25922. }
  25923. this._indices = indices;
  25924. if (this._meshes.length !== 0 && this._indices) {
  25925. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25926. }
  25927. if (totalVertices !== undefined) {
  25928. this._totalVertices = totalVertices;
  25929. }
  25930. var meshes = this._meshes;
  25931. var numOfMeshes = meshes.length;
  25932. for (var index = 0; index < numOfMeshes; index++) {
  25933. meshes[index]._createGlobalSubMesh();
  25934. }
  25935. this.notifyUpdate();
  25936. };
  25937. Geometry.prototype.getTotalIndices = function () {
  25938. if (!this.isReady()) {
  25939. return 0;
  25940. }
  25941. return this._indices.length;
  25942. };
  25943. Geometry.prototype.getIndices = function (copyWhenShared) {
  25944. if (!this.isReady()) {
  25945. return null;
  25946. }
  25947. var orig = this._indices;
  25948. if (!copyWhenShared || this._meshes.length === 1) {
  25949. return orig;
  25950. }
  25951. else {
  25952. var len = orig.length;
  25953. var copy = [];
  25954. for (var i = 0; i < len; i++) {
  25955. copy.push(orig[i]);
  25956. }
  25957. return copy;
  25958. }
  25959. };
  25960. Geometry.prototype.getIndexBuffer = function () {
  25961. if (!this.isReady()) {
  25962. return null;
  25963. }
  25964. return this._indexBuffer;
  25965. };
  25966. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25967. var meshes = this._meshes;
  25968. var index = meshes.indexOf(mesh);
  25969. if (index === -1) {
  25970. return;
  25971. }
  25972. for (var kind in this._vertexBuffers) {
  25973. this._vertexBuffers[kind].dispose();
  25974. }
  25975. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25976. this._indexBuffer = null;
  25977. }
  25978. meshes.splice(index, 1);
  25979. mesh._geometry = null;
  25980. if (meshes.length === 0 && shouldDispose) {
  25981. this.dispose();
  25982. }
  25983. };
  25984. Geometry.prototype.applyToMesh = function (mesh) {
  25985. if (mesh._geometry === this) {
  25986. return;
  25987. }
  25988. var previousGeometry = mesh._geometry;
  25989. if (previousGeometry) {
  25990. previousGeometry.releaseForMesh(mesh);
  25991. }
  25992. var meshes = this._meshes;
  25993. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25994. mesh._geometry = this;
  25995. this._scene.pushGeometry(this);
  25996. meshes.push(mesh);
  25997. if (this.isReady()) {
  25998. this._applyToMesh(mesh);
  25999. }
  26000. else {
  26001. mesh._boundingInfo = this._boundingInfo;
  26002. }
  26003. };
  26004. Geometry.prototype._applyToMesh = function (mesh) {
  26005. var numOfMeshes = this._meshes.length;
  26006. // vertexBuffers
  26007. for (var kind in this._vertexBuffers) {
  26008. if (numOfMeshes === 1) {
  26009. this._vertexBuffers[kind].create();
  26010. }
  26011. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26012. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26013. mesh._resetPointsArrayCache();
  26014. if (!this._extend) {
  26015. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26016. }
  26017. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26018. mesh._createGlobalSubMesh();
  26019. //bounding info was just created again, world matrix should be applied again.
  26020. mesh._updateBoundingInfo();
  26021. }
  26022. }
  26023. // indexBuffer
  26024. if (numOfMeshes === 1 && this._indices) {
  26025. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26026. }
  26027. if (this._indexBuffer) {
  26028. this._indexBuffer.references = numOfMeshes;
  26029. }
  26030. };
  26031. Geometry.prototype.notifyUpdate = function (kind) {
  26032. if (this.onGeometryUpdated) {
  26033. this.onGeometryUpdated(this, kind);
  26034. }
  26035. };
  26036. Geometry.prototype.load = function (scene, onLoaded) {
  26037. var _this = this;
  26038. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26039. return;
  26040. }
  26041. if (this.isReady()) {
  26042. if (onLoaded) {
  26043. onLoaded();
  26044. }
  26045. return;
  26046. }
  26047. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26048. scene._addPendingData(this);
  26049. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26050. _this._delayLoadingFunction(JSON.parse(data), _this);
  26051. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26052. _this._delayInfo = [];
  26053. scene._removePendingData(_this);
  26054. var meshes = _this._meshes;
  26055. var numOfMeshes = meshes.length;
  26056. for (var index = 0; index < numOfMeshes; index++) {
  26057. _this._applyToMesh(meshes[index]);
  26058. }
  26059. if (onLoaded) {
  26060. onLoaded();
  26061. }
  26062. }, function () { }, scene.database);
  26063. };
  26064. Geometry.prototype.isDisposed = function () {
  26065. return this._isDisposed;
  26066. };
  26067. Geometry.prototype.dispose = function () {
  26068. var meshes = this._meshes;
  26069. var numOfMeshes = meshes.length;
  26070. var index;
  26071. for (index = 0; index < numOfMeshes; index++) {
  26072. this.releaseForMesh(meshes[index]);
  26073. }
  26074. this._meshes = [];
  26075. for (var kind in this._vertexBuffers) {
  26076. this._vertexBuffers[kind].dispose();
  26077. }
  26078. this._vertexBuffers = [];
  26079. this._totalVertices = 0;
  26080. if (this._indexBuffer) {
  26081. this._engine._releaseBuffer(this._indexBuffer);
  26082. }
  26083. this._indexBuffer = null;
  26084. this._indices = [];
  26085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26086. this.delayLoadingFile = null;
  26087. this._delayLoadingFunction = null;
  26088. this._delayInfo = [];
  26089. this._boundingInfo = null;
  26090. this._scene.removeGeometry(this);
  26091. this._isDisposed = true;
  26092. };
  26093. Geometry.prototype.copy = function (id) {
  26094. var vertexData = new BABYLON.VertexData();
  26095. vertexData.indices = [];
  26096. var indices = this.getIndices();
  26097. for (var index = 0; index < indices.length; index++) {
  26098. vertexData.indices.push(indices[index]);
  26099. }
  26100. var updatable = false;
  26101. var stopChecking = false;
  26102. var kind;
  26103. for (kind in this._vertexBuffers) {
  26104. // using slice() to make a copy of the array and not just reference it
  26105. var data = this.getVerticesData(kind);
  26106. if (data instanceof Float32Array) {
  26107. vertexData.set(new Float32Array(data), kind);
  26108. }
  26109. else {
  26110. vertexData.set(data.slice(0), kind);
  26111. }
  26112. if (!stopChecking) {
  26113. updatable = this.getVertexBuffer(kind).isUpdatable();
  26114. stopChecking = !updatable;
  26115. }
  26116. }
  26117. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26118. geometry.delayLoadState = this.delayLoadState;
  26119. geometry.delayLoadingFile = this.delayLoadingFile;
  26120. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26121. for (kind in this._delayInfo) {
  26122. geometry._delayInfo = geometry._delayInfo || [];
  26123. geometry._delayInfo.push(kind);
  26124. }
  26125. // Bounding info
  26126. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26127. return geometry;
  26128. };
  26129. // Statics
  26130. Geometry.ExtractFromMesh = function (mesh, id) {
  26131. var geometry = mesh._geometry;
  26132. if (!geometry) {
  26133. return null;
  26134. }
  26135. return geometry.copy(id);
  26136. };
  26137. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26138. // be aware Math.random() could cause collisions
  26139. Geometry.RandomId = function () {
  26140. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26141. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26142. return v.toString(16);
  26143. });
  26144. };
  26145. return Geometry;
  26146. })();
  26147. BABYLON.Geometry = Geometry;
  26148. /////// Primitives //////////////////////////////////////////////
  26149. var Geometry;
  26150. (function (Geometry) {
  26151. var Primitives;
  26152. (function (Primitives) {
  26153. /// Abstract class
  26154. var _Primitive = (function (_super) {
  26155. __extends(_Primitive, _super);
  26156. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26157. this._beingRegenerated = true;
  26158. this._canBeRegenerated = canBeRegenerated;
  26159. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26160. this._beingRegenerated = false;
  26161. }
  26162. _Primitive.prototype.canBeRegenerated = function () {
  26163. return this._canBeRegenerated;
  26164. };
  26165. _Primitive.prototype.regenerate = function () {
  26166. if (!this._canBeRegenerated) {
  26167. return;
  26168. }
  26169. this._beingRegenerated = true;
  26170. this.setAllVerticesData(this._regenerateVertexData(), false);
  26171. this._beingRegenerated = false;
  26172. };
  26173. _Primitive.prototype.asNewGeometry = function (id) {
  26174. return _super.prototype.copy.call(this, id);
  26175. };
  26176. // overrides
  26177. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26178. if (!this._beingRegenerated) {
  26179. return;
  26180. }
  26181. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26182. };
  26183. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26184. if (!this._beingRegenerated) {
  26185. return;
  26186. }
  26187. _super.prototype.setVerticesData.call(this, kind, data, false);
  26188. };
  26189. // to override
  26190. // protected
  26191. _Primitive.prototype._regenerateVertexData = function () {
  26192. throw new Error("Abstract method");
  26193. };
  26194. _Primitive.prototype.copy = function (id) {
  26195. throw new Error("Must be overriden in sub-classes.");
  26196. };
  26197. return _Primitive;
  26198. })(Geometry);
  26199. Primitives._Primitive = _Primitive;
  26200. var Ribbon = (function (_super) {
  26201. __extends(Ribbon, _super);
  26202. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26204. this.pathArray = pathArray;
  26205. this.closeArray = closeArray;
  26206. this.closePath = closePath;
  26207. this.offset = offset;
  26208. this.side = side;
  26209. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26210. }
  26211. Ribbon.prototype._regenerateVertexData = function () {
  26212. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26213. };
  26214. Ribbon.prototype.copy = function (id) {
  26215. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26216. };
  26217. return Ribbon;
  26218. })(_Primitive);
  26219. Primitives.Ribbon = Ribbon;
  26220. var Box = (function (_super) {
  26221. __extends(Box, _super);
  26222. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26223. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26224. this.size = size;
  26225. this.side = side;
  26226. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26227. }
  26228. Box.prototype._regenerateVertexData = function () {
  26229. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26230. };
  26231. Box.prototype.copy = function (id) {
  26232. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26233. };
  26234. return Box;
  26235. })(_Primitive);
  26236. Primitives.Box = Box;
  26237. var Sphere = (function (_super) {
  26238. __extends(Sphere, _super);
  26239. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26240. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26241. this.segments = segments;
  26242. this.diameter = diameter;
  26243. this.side = side;
  26244. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26245. }
  26246. Sphere.prototype._regenerateVertexData = function () {
  26247. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26248. };
  26249. Sphere.prototype.copy = function (id) {
  26250. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26251. };
  26252. return Sphere;
  26253. })(_Primitive);
  26254. Primitives.Sphere = Sphere;
  26255. var Disc = (function (_super) {
  26256. __extends(Disc, _super);
  26257. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26259. this.radius = radius;
  26260. this.tessellation = tessellation;
  26261. this.side = side;
  26262. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26263. }
  26264. Disc.prototype._regenerateVertexData = function () {
  26265. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26266. };
  26267. Disc.prototype.copy = function (id) {
  26268. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26269. };
  26270. return Disc;
  26271. })(_Primitive);
  26272. Primitives.Disc = Disc;
  26273. var Cylinder = (function (_super) {
  26274. __extends(Cylinder, _super);
  26275. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26276. if (subdivisions === void 0) { subdivisions = 1; }
  26277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26278. this.height = height;
  26279. this.diameterTop = diameterTop;
  26280. this.diameterBottom = diameterBottom;
  26281. this.tessellation = tessellation;
  26282. this.subdivisions = subdivisions;
  26283. this.side = side;
  26284. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26285. }
  26286. Cylinder.prototype._regenerateVertexData = function () {
  26287. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26288. };
  26289. Cylinder.prototype.copy = function (id) {
  26290. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26291. };
  26292. return Cylinder;
  26293. })(_Primitive);
  26294. Primitives.Cylinder = Cylinder;
  26295. var Torus = (function (_super) {
  26296. __extends(Torus, _super);
  26297. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26298. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26299. this.diameter = diameter;
  26300. this.thickness = thickness;
  26301. this.tessellation = tessellation;
  26302. this.side = side;
  26303. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26304. }
  26305. Torus.prototype._regenerateVertexData = function () {
  26306. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26307. };
  26308. Torus.prototype.copy = function (id) {
  26309. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26310. };
  26311. return Torus;
  26312. })(_Primitive);
  26313. Primitives.Torus = Torus;
  26314. var Ground = (function (_super) {
  26315. __extends(Ground, _super);
  26316. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26317. this.width = width;
  26318. this.height = height;
  26319. this.subdivisions = subdivisions;
  26320. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26321. }
  26322. Ground.prototype._regenerateVertexData = function () {
  26323. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26324. };
  26325. Ground.prototype.copy = function (id) {
  26326. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26327. };
  26328. return Ground;
  26329. })(_Primitive);
  26330. Primitives.Ground = Ground;
  26331. var TiledGround = (function (_super) {
  26332. __extends(TiledGround, _super);
  26333. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26334. this.xmin = xmin;
  26335. this.zmin = zmin;
  26336. this.xmax = xmax;
  26337. this.zmax = zmax;
  26338. this.subdivisions = subdivisions;
  26339. this.precision = precision;
  26340. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26341. }
  26342. TiledGround.prototype._regenerateVertexData = function () {
  26343. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26344. };
  26345. TiledGround.prototype.copy = function (id) {
  26346. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26347. };
  26348. return TiledGround;
  26349. })(_Primitive);
  26350. Primitives.TiledGround = TiledGround;
  26351. var Plane = (function (_super) {
  26352. __extends(Plane, _super);
  26353. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26354. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26355. this.size = size;
  26356. this.side = side;
  26357. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26358. }
  26359. Plane.prototype._regenerateVertexData = function () {
  26360. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26361. };
  26362. Plane.prototype.copy = function (id) {
  26363. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26364. };
  26365. return Plane;
  26366. })(_Primitive);
  26367. Primitives.Plane = Plane;
  26368. var TorusKnot = (function (_super) {
  26369. __extends(TorusKnot, _super);
  26370. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26371. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26372. this.radius = radius;
  26373. this.tube = tube;
  26374. this.radialSegments = radialSegments;
  26375. this.tubularSegments = tubularSegments;
  26376. this.p = p;
  26377. this.q = q;
  26378. this.side = side;
  26379. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26380. }
  26381. TorusKnot.prototype._regenerateVertexData = function () {
  26382. 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 });
  26383. };
  26384. TorusKnot.prototype.copy = function (id) {
  26385. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26386. };
  26387. return TorusKnot;
  26388. })(_Primitive);
  26389. Primitives.TorusKnot = TorusKnot;
  26390. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26391. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26392. })(BABYLON || (BABYLON = {}));
  26393. var BABYLON;
  26394. (function (BABYLON) {
  26395. var GroundMesh = (function (_super) {
  26396. __extends(GroundMesh, _super);
  26397. function GroundMesh(name, scene) {
  26398. _super.call(this, name, scene);
  26399. this.generateOctree = false;
  26400. this._worldInverse = new BABYLON.Matrix();
  26401. }
  26402. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26403. get: function () {
  26404. return this._subdivisions;
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26410. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26411. this._subdivisions = chunksCount;
  26412. this.subdivide(this._subdivisions);
  26413. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26414. };
  26415. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26416. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26417. this.getWorldMatrix().invertToRef(this._worldInverse);
  26418. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26419. var pickInfo = this.intersects(ray);
  26420. if (pickInfo.hit) {
  26421. return pickInfo.pickedPoint.y;
  26422. }
  26423. return 0;
  26424. };
  26425. return GroundMesh;
  26426. })(BABYLON.Mesh);
  26427. BABYLON.GroundMesh = GroundMesh;
  26428. })(BABYLON || (BABYLON = {}));
  26429. var BABYLON;
  26430. (function (BABYLON) {
  26431. var LinesMesh = (function (_super) {
  26432. __extends(LinesMesh, _super);
  26433. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26434. if (parent === void 0) { parent = null; }
  26435. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26436. this.color = new BABYLON.Color3(1, 1, 1);
  26437. this.alpha = 1;
  26438. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26439. attributes: ["position"],
  26440. uniforms: ["worldViewProjection", "color"],
  26441. needAlphaBlending: true
  26442. });
  26443. }
  26444. Object.defineProperty(LinesMesh.prototype, "material", {
  26445. get: function () {
  26446. return this._colorShader;
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26452. get: function () {
  26453. return false;
  26454. },
  26455. enumerable: true,
  26456. configurable: true
  26457. });
  26458. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26459. get: function () {
  26460. return false;
  26461. },
  26462. enumerable: true,
  26463. configurable: true
  26464. });
  26465. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26466. var engine = this.getScene().getEngine();
  26467. var indexToBind = this._geometry.getIndexBuffer();
  26468. // VBOs
  26469. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26470. // Color
  26471. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26472. };
  26473. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26474. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26475. return;
  26476. }
  26477. var engine = this.getScene().getEngine();
  26478. // Draw order
  26479. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26480. };
  26481. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26482. return null;
  26483. };
  26484. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26485. this._colorShader.dispose();
  26486. _super.prototype.dispose.call(this, doNotRecurse);
  26487. };
  26488. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26489. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26490. };
  26491. return LinesMesh;
  26492. })(BABYLON.Mesh);
  26493. BABYLON.LinesMesh = LinesMesh;
  26494. })(BABYLON || (BABYLON = {}));
  26495. var BABYLON;
  26496. (function (BABYLON) {
  26497. var DebugLayer = (function () {
  26498. function DebugLayer(scene) {
  26499. var _this = this;
  26500. this._transformationMatrix = BABYLON.Matrix.Identity();
  26501. this._enabled = false;
  26502. this._labelsEnabled = false;
  26503. this._displayStatistics = true;
  26504. this._displayTree = false;
  26505. this._displayLogs = false;
  26506. this._identityMatrix = BABYLON.Matrix.Identity();
  26507. this.axisRatio = 0.02;
  26508. this.accentColor = "orange";
  26509. this._scene = scene;
  26510. this._syncPositions = function () {
  26511. var engine = _this._scene.getEngine();
  26512. var canvasRect = engine.getRenderingCanvasClientRect();
  26513. if (_this._showUI) {
  26514. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26515. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26516. _this._statsDiv.style.width = "400px";
  26517. _this._statsDiv.style.height = "auto";
  26518. _this._statsSubsetDiv.style.maxHeight = "240px";
  26519. _this._optionsDiv.style.left = "0px";
  26520. _this._optionsDiv.style.top = "10px";
  26521. _this._optionsDiv.style.width = "200px";
  26522. _this._optionsDiv.style.height = "auto";
  26523. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26524. _this._logDiv.style.left = "0px";
  26525. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26526. _this._logDiv.style.width = "600px";
  26527. _this._logDiv.style.height = "160px";
  26528. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26529. _this._treeDiv.style.top = "10px";
  26530. _this._treeDiv.style.width = "300px";
  26531. _this._treeDiv.style.height = "auto";
  26532. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26533. }
  26534. _this._globalDiv.style.left = canvasRect.left + "px";
  26535. _this._globalDiv.style.top = canvasRect.top + "px";
  26536. _this._drawingCanvas.style.left = "0px";
  26537. _this._drawingCanvas.style.top = "0px";
  26538. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26539. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26540. var devicePixelRatio = window.devicePixelRatio || 1;
  26541. var context = _this._drawingContext;
  26542. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26543. context.mozBackingStorePixelRatio ||
  26544. context.msBackingStorePixelRatio ||
  26545. context.oBackingStorePixelRatio ||
  26546. context.backingStorePixelRatio || 1;
  26547. _this._ratio = devicePixelRatio / backingStoreRatio;
  26548. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26549. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26550. };
  26551. this._onCanvasClick = function (evt) {
  26552. _this._clickPosition = {
  26553. x: evt.clientX * _this._ratio,
  26554. y: evt.clientY * _this._ratio
  26555. };
  26556. };
  26557. this._syncUI = function () {
  26558. if (_this._showUI) {
  26559. if (_this._displayStatistics) {
  26560. _this._displayStats();
  26561. _this._statsDiv.style.display = "";
  26562. }
  26563. else {
  26564. _this._statsDiv.style.display = "none";
  26565. }
  26566. if (_this._displayLogs) {
  26567. _this._logDiv.style.display = "";
  26568. }
  26569. else {
  26570. _this._logDiv.style.display = "none";
  26571. }
  26572. if (_this._displayTree) {
  26573. _this._treeDiv.style.display = "";
  26574. if (_this._needToRefreshMeshesTree) {
  26575. _this._needToRefreshMeshesTree = false;
  26576. _this._refreshMeshesTreeContent();
  26577. }
  26578. }
  26579. else {
  26580. _this._treeDiv.style.display = "none";
  26581. }
  26582. }
  26583. };
  26584. this._syncData = function () {
  26585. if (_this._labelsEnabled || !_this._showUI) {
  26586. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26587. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26588. var engine = _this._scene.getEngine();
  26589. var viewport = _this._camera.viewport;
  26590. var globalViewport = viewport.toGlobal(engine);
  26591. // Meshes
  26592. var meshes = _this._camera.getActiveMeshes();
  26593. for (var index = 0; index < meshes.length; index++) {
  26594. var mesh = meshes.data[index];
  26595. var position = mesh.getBoundingInfo().boundingSphere.center;
  26596. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26597. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26598. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26599. }
  26600. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26601. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26602. }
  26603. }
  26604. // Cameras
  26605. var cameras = _this._scene.cameras;
  26606. for (index = 0; index < cameras.length; index++) {
  26607. var camera = cameras[index];
  26608. if (camera === _this._camera) {
  26609. continue;
  26610. }
  26611. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26612. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26613. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26614. _this._camera.detachControl(engine.getRenderingCanvas());
  26615. _this._camera = camera;
  26616. _this._camera.attachControl(engine.getRenderingCanvas());
  26617. }, function () { return "purple"; });
  26618. }
  26619. }
  26620. // Lights
  26621. var lights = _this._scene.lights;
  26622. for (index = 0; index < lights.length; index++) {
  26623. var light = lights[index];
  26624. if (light.position) {
  26625. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26626. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26627. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26628. light.setEnabled(!light.isEnabled());
  26629. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26630. }
  26631. }
  26632. }
  26633. }
  26634. _this._clickPosition = undefined;
  26635. };
  26636. }
  26637. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26638. while (this._treeSubsetDiv.hasChildNodes()) {
  26639. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26640. }
  26641. // Add meshes
  26642. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26643. sortedArray.sort(function (a, b) {
  26644. if (a.name === b.name) {
  26645. return 0;
  26646. }
  26647. return (a.name > b.name) ? 1 : -1;
  26648. });
  26649. for (var index = 0; index < sortedArray.length; index++) {
  26650. var mesh = sortedArray[index];
  26651. if (!mesh.isEnabled()) {
  26652. continue;
  26653. }
  26654. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26655. m.isVisible = element.checked;
  26656. }, mesh);
  26657. }
  26658. };
  26659. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26660. this._drawingContext.beginPath();
  26661. this._drawingContext.moveTo(zero.x, zero.y);
  26662. this._drawingContext.lineTo(unit.x, unit.y);
  26663. this._drawingContext.strokeStyle = color;
  26664. this._drawingContext.lineWidth = 4;
  26665. this._drawingContext.stroke();
  26666. this._drawingContext.font = "normal 14px Segoe UI";
  26667. this._drawingContext.fillStyle = color;
  26668. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26669. };
  26670. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26671. var position = mesh.getBoundingInfo().boundingSphere.center;
  26672. var worldMatrix = mesh.getWorldMatrix();
  26673. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26674. var unit = (unprojectedVector.subtract(position)).length();
  26675. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26676. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26677. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26678. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26679. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26680. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26681. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26682. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26683. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26684. };
  26685. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26686. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26687. this._drawingContext.font = "normal 12px Segoe UI";
  26688. var textMetrics = this._drawingContext.measureText(text);
  26689. var centerX = projectedPosition.x - textMetrics.width / 2;
  26690. var centerY = projectedPosition.y;
  26691. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26692. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26693. onClick();
  26694. }
  26695. this._drawingContext.beginPath();
  26696. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26697. this._drawingContext.fillStyle = getFillStyle();
  26698. this._drawingContext.globalAlpha = 0.5;
  26699. this._drawingContext.fill();
  26700. this._drawingContext.globalAlpha = 1.0;
  26701. this._drawingContext.strokeStyle = '#FFFFFF';
  26702. this._drawingContext.lineWidth = 1;
  26703. this._drawingContext.stroke();
  26704. this._drawingContext.fillStyle = "#FFFFFF";
  26705. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26706. this._drawingContext.beginPath();
  26707. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26708. this._drawingContext.fill();
  26709. }
  26710. };
  26711. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26712. if (!this._clickPosition) {
  26713. return false;
  26714. }
  26715. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26716. return false;
  26717. }
  26718. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26719. return false;
  26720. }
  26721. return true;
  26722. };
  26723. DebugLayer.prototype.isVisible = function () {
  26724. return this._enabled;
  26725. };
  26726. DebugLayer.prototype.hide = function () {
  26727. if (!this._enabled) {
  26728. return;
  26729. }
  26730. this._enabled = false;
  26731. var engine = this._scene.getEngine();
  26732. this._scene.unregisterBeforeRender(this._syncData);
  26733. this._scene.unregisterAfterRender(this._syncUI);
  26734. this._rootElement.removeChild(this._globalDiv);
  26735. this._scene.forceShowBoundingBoxes = false;
  26736. this._scene.forceWireframe = false;
  26737. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26738. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26739. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26740. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26741. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26742. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26743. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26744. BABYLON.StandardMaterial.LightmapEnabled = true;
  26745. this._scene.shadowsEnabled = true;
  26746. this._scene.particlesEnabled = true;
  26747. this._scene.postProcessesEnabled = true;
  26748. this._scene.collisionsEnabled = true;
  26749. this._scene.lightsEnabled = true;
  26750. this._scene.texturesEnabled = true;
  26751. this._scene.lensFlaresEnabled = true;
  26752. this._scene.proceduralTexturesEnabled = true;
  26753. this._scene.renderTargetsEnabled = true;
  26754. this._scene.probesEnabled = true;
  26755. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26756. };
  26757. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26758. if (showUI === void 0) { showUI = true; }
  26759. if (camera === void 0) { camera = null; }
  26760. if (rootElement === void 0) { rootElement = null; }
  26761. if (this._enabled) {
  26762. return;
  26763. }
  26764. this._enabled = true;
  26765. if (camera) {
  26766. this._camera = camera;
  26767. }
  26768. else {
  26769. this._camera = this._scene.activeCamera;
  26770. }
  26771. this._showUI = showUI;
  26772. var engine = this._scene.getEngine();
  26773. this._globalDiv = document.createElement("div");
  26774. this._rootElement = rootElement || document.body;
  26775. this._rootElement.appendChild(this._globalDiv);
  26776. this._generateDOMelements();
  26777. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26778. this._syncPositions();
  26779. this._scene.registerBeforeRender(this._syncData);
  26780. this._scene.registerAfterRender(this._syncUI);
  26781. };
  26782. DebugLayer.prototype._clearLabels = function () {
  26783. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26784. for (var index = 0; index < this._scene.meshes.length; index++) {
  26785. var mesh = this._scene.meshes[index];
  26786. mesh.renderOverlay = false;
  26787. }
  26788. };
  26789. DebugLayer.prototype._generateheader = function (root, text) {
  26790. var header = document.createElement("div");
  26791. header.innerHTML = text + "&nbsp;";
  26792. header.style.textAlign = "right";
  26793. header.style.width = "100%";
  26794. header.style.color = "white";
  26795. header.style.backgroundColor = "Black";
  26796. header.style.padding = "5px 5px 4px 0px";
  26797. header.style.marginLeft = "-5px";
  26798. header.style.fontWeight = "bold";
  26799. root.appendChild(header);
  26800. };
  26801. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26802. var label = document.createElement("label");
  26803. label.innerHTML = title;
  26804. label.style.color = color;
  26805. root.appendChild(label);
  26806. root.appendChild(document.createElement("br"));
  26807. };
  26808. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26809. if (tag === void 0) { tag = null; }
  26810. var label = document.createElement("label");
  26811. var boundingBoxesCheckbox = document.createElement("input");
  26812. boundingBoxesCheckbox.type = "checkbox";
  26813. boundingBoxesCheckbox.checked = initialState;
  26814. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26815. task(evt.target, tag);
  26816. });
  26817. label.appendChild(boundingBoxesCheckbox);
  26818. var container = document.createElement("span");
  26819. var leftPart = document.createElement("span");
  26820. var rightPart = document.createElement("span");
  26821. rightPart.style.cssFloat = "right";
  26822. leftPart.innerHTML = leftTitle;
  26823. rightPart.innerHTML = rightTitle;
  26824. rightPart.style.fontSize = "12px";
  26825. rightPart.style.maxWidth = "200px";
  26826. container.appendChild(leftPart);
  26827. container.appendChild(rightPart);
  26828. label.appendChild(container);
  26829. root.appendChild(label);
  26830. root.appendChild(document.createElement("br"));
  26831. };
  26832. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26833. if (tag === void 0) { tag = null; }
  26834. var label = document.createElement("label");
  26835. var checkBox = document.createElement("input");
  26836. checkBox.type = "checkbox";
  26837. checkBox.checked = initialState;
  26838. checkBox.addEventListener("change", function (evt) {
  26839. task(evt.target, tag);
  26840. });
  26841. label.appendChild(checkBox);
  26842. label.appendChild(document.createTextNode(title));
  26843. root.appendChild(label);
  26844. root.appendChild(document.createElement("br"));
  26845. };
  26846. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26847. if (tag === void 0) { tag = null; }
  26848. var button = document.createElement("button");
  26849. button.innerHTML = title;
  26850. button.style.height = "24px";
  26851. button.style.color = "#444444";
  26852. button.style.border = "1px solid white";
  26853. button.className = "debugLayerButton";
  26854. button.addEventListener("click", function (evt) {
  26855. task(evt.target, tag);
  26856. });
  26857. root.appendChild(button);
  26858. root.appendChild(document.createElement("br"));
  26859. };
  26860. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26861. if (tag === void 0) { tag = null; }
  26862. var label = document.createElement("label");
  26863. var boundingBoxesRadio = document.createElement("input");
  26864. boundingBoxesRadio.type = "radio";
  26865. boundingBoxesRadio.name = name;
  26866. boundingBoxesRadio.checked = initialState;
  26867. boundingBoxesRadio.addEventListener("change", function (evt) {
  26868. task(evt.target, tag);
  26869. });
  26870. label.appendChild(boundingBoxesRadio);
  26871. label.appendChild(document.createTextNode(title));
  26872. root.appendChild(label);
  26873. root.appendChild(document.createElement("br"));
  26874. };
  26875. DebugLayer.prototype._generateDOMelements = function () {
  26876. var _this = this;
  26877. this._globalDiv.id = "DebugLayer";
  26878. this._globalDiv.style.position = "absolute";
  26879. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26880. this._globalDiv.style.fontSize = "14px";
  26881. this._globalDiv.style.color = "white";
  26882. // Drawing canvas
  26883. this._drawingCanvas = document.createElement("canvas");
  26884. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26885. this._drawingCanvas.style.position = "absolute";
  26886. this._drawingCanvas.style.pointerEvents = "none";
  26887. this._drawingCanvas.style.backgroundColor = "transparent";
  26888. this._drawingContext = this._drawingCanvas.getContext("2d");
  26889. this._globalDiv.appendChild(this._drawingCanvas);
  26890. if (this._showUI) {
  26891. var background = "rgba(128, 128, 128, 0.4)";
  26892. var border = "rgb(180, 180, 180) solid 1px";
  26893. // Stats
  26894. this._statsDiv = document.createElement("div");
  26895. this._statsDiv.id = "DebugLayerStats";
  26896. this._statsDiv.style.border = border;
  26897. this._statsDiv.style.position = "absolute";
  26898. this._statsDiv.style.background = background;
  26899. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26900. this._generateheader(this._statsDiv, "STATISTICS");
  26901. this._statsSubsetDiv = document.createElement("div");
  26902. this._statsSubsetDiv.style.paddingTop = "5px";
  26903. this._statsSubsetDiv.style.paddingBottom = "5px";
  26904. this._statsSubsetDiv.style.overflowY = "auto";
  26905. this._statsDiv.appendChild(this._statsSubsetDiv);
  26906. // Tree
  26907. this._treeDiv = document.createElement("div");
  26908. this._treeDiv.id = "DebugLayerTree";
  26909. this._treeDiv.style.border = border;
  26910. this._treeDiv.style.position = "absolute";
  26911. this._treeDiv.style.background = background;
  26912. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26913. this._treeDiv.style.display = "none";
  26914. this._generateheader(this._treeDiv, "MESHES TREE");
  26915. this._treeSubsetDiv = document.createElement("div");
  26916. this._treeSubsetDiv.style.paddingTop = "5px";
  26917. this._treeSubsetDiv.style.paddingRight = "5px";
  26918. this._treeSubsetDiv.style.overflowY = "auto";
  26919. this._treeSubsetDiv.style.maxHeight = "300px";
  26920. this._treeDiv.appendChild(this._treeSubsetDiv);
  26921. this._needToRefreshMeshesTree = true;
  26922. // Logs
  26923. this._logDiv = document.createElement("div");
  26924. this._logDiv.style.border = border;
  26925. this._logDiv.id = "DebugLayerLogs";
  26926. this._logDiv.style.position = "absolute";
  26927. this._logDiv.style.background = background;
  26928. this._logDiv.style.padding = "0px 0px 0px 5px";
  26929. this._logDiv.style.display = "none";
  26930. this._generateheader(this._logDiv, "LOGS");
  26931. this._logSubsetDiv = document.createElement("div");
  26932. this._logSubsetDiv.style.height = "127px";
  26933. this._logSubsetDiv.style.paddingTop = "5px";
  26934. this._logSubsetDiv.style.overflowY = "auto";
  26935. this._logSubsetDiv.style.fontSize = "12px";
  26936. this._logSubsetDiv.style.fontFamily = "consolas";
  26937. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26938. this._logDiv.appendChild(this._logSubsetDiv);
  26939. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26940. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26941. };
  26942. // Options
  26943. this._optionsDiv = document.createElement("div");
  26944. this._optionsDiv.id = "DebugLayerOptions";
  26945. this._optionsDiv.style.border = border;
  26946. this._optionsDiv.style.position = "absolute";
  26947. this._optionsDiv.style.background = background;
  26948. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26949. this._optionsDiv.style.overflowY = "auto";
  26950. this._generateheader(this._optionsDiv, "OPTIONS");
  26951. this._optionsSubsetDiv = document.createElement("div");
  26952. this._optionsSubsetDiv.style.paddingTop = "5px";
  26953. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26954. this._optionsSubsetDiv.style.overflowY = "auto";
  26955. this._optionsSubsetDiv.style.maxHeight = "200px";
  26956. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26957. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26958. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  26959. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  26960. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26961. _this._displayTree = element.checked;
  26962. _this._needToRefreshMeshesTree = true;
  26963. });
  26964. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26965. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26966. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  26967. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26968. _this._labelsEnabled = element.checked;
  26969. if (!_this._labelsEnabled) {
  26970. _this._clearLabels();
  26971. }
  26972. });
  26973. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26974. if (element.checked) {
  26975. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26976. }
  26977. else {
  26978. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26979. }
  26980. });
  26981. ;
  26982. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26983. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26984. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26985. if (element.checked) {
  26986. _this._scene.forceWireframe = false;
  26987. _this._scene.forcePointsCloud = false;
  26988. }
  26989. });
  26990. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26991. if (element.checked) {
  26992. _this._scene.forceWireframe = true;
  26993. _this._scene.forcePointsCloud = false;
  26994. }
  26995. });
  26996. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26997. if (element.checked) {
  26998. _this._scene.forceWireframe = false;
  26999. _this._scene.forcePointsCloud = true;
  27000. }
  27001. });
  27002. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27003. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27004. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27005. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27006. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27007. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27008. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27009. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27010. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27011. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27012. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27013. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27014. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27015. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27016. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27017. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27018. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27019. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27020. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27021. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27022. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27023. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27024. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27025. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27026. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27027. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27028. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27029. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27030. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27031. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27032. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27033. if (element.checked) {
  27034. _this._scene.headphone = true;
  27035. }
  27036. });
  27037. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27038. if (element.checked) {
  27039. _this._scene.headphone = false;
  27040. }
  27041. });
  27042. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27043. _this._scene.audioEnabled = !element.checked;
  27044. });
  27045. }
  27046. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27047. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27048. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27049. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27050. this._globalDiv.appendChild(this._statsDiv);
  27051. this._globalDiv.appendChild(this._logDiv);
  27052. this._globalDiv.appendChild(this._optionsDiv);
  27053. this._globalDiv.appendChild(this._treeDiv);
  27054. }
  27055. };
  27056. DebugLayer.prototype._displayStats = function () {
  27057. var scene = this._scene;
  27058. var engine = scene.getEngine();
  27059. var glInfo = engine.getGlInfo();
  27060. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27061. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27062. + "<b>Count</b><br>"
  27063. + "Total meshes: " + scene.meshes.length + "<br>"
  27064. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27065. + "Total materials: " + scene.materials.length + "<br>"
  27066. + "Total textures: " + scene.textures.length + "<br>"
  27067. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27068. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27069. + "Active bones: " + scene.getActiveBones() + "<br>"
  27070. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27071. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27072. + "<b>Duration</b><br>"
  27073. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27074. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27075. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27076. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27077. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27078. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27079. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27080. + "</div>"
  27081. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27082. + "<b>Extensions</b><br>"
  27083. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27084. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27085. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27086. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27087. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27088. + "<b>Caps.</b><br>"
  27089. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27090. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27091. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27092. + "</div><br>"
  27093. + "<b>Info</b><br>"
  27094. + glInfo.version + "<br>"
  27095. + glInfo.renderer + "<br>";
  27096. if (this.customStatsFunction) {
  27097. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27098. }
  27099. };
  27100. return DebugLayer;
  27101. })();
  27102. BABYLON.DebugLayer = DebugLayer;
  27103. })(BABYLON || (BABYLON = {}));
  27104. var BABYLON;
  27105. (function (BABYLON) {
  27106. var DefaultLoadingScreen = (function () {
  27107. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27108. var _this = this;
  27109. if (_loadingText === void 0) { _loadingText = ""; }
  27110. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27111. this._renderingCanvas = _renderingCanvas;
  27112. this._loadingText = _loadingText;
  27113. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27114. // Resize
  27115. this._resizeLoadingUI = function () {
  27116. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27117. _this._loadingDiv.style.position = "absolute";
  27118. _this._loadingDiv.style.left = canvasRect.left + "px";
  27119. _this._loadingDiv.style.top = canvasRect.top + "px";
  27120. _this._loadingDiv.style.width = canvasRect.width + "px";
  27121. _this._loadingDiv.style.height = canvasRect.height + "px";
  27122. };
  27123. }
  27124. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27125. var _this = this;
  27126. this._loadingDiv = document.createElement("div");
  27127. this._loadingDiv.style.opacity = "0";
  27128. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27129. // Loading text
  27130. this._loadingTextDiv = document.createElement("div");
  27131. this._loadingTextDiv.style.position = "absolute";
  27132. this._loadingTextDiv.style.left = "0";
  27133. this._loadingTextDiv.style.top = "50%";
  27134. this._loadingTextDiv.style.marginTop = "80px";
  27135. this._loadingTextDiv.style.width = "100%";
  27136. this._loadingTextDiv.style.height = "20px";
  27137. this._loadingTextDiv.style.fontFamily = "Arial";
  27138. this._loadingTextDiv.style.fontSize = "14px";
  27139. this._loadingTextDiv.style.color = "white";
  27140. this._loadingTextDiv.style.textAlign = "center";
  27141. this._loadingTextDiv.innerHTML = "Loading";
  27142. this._loadingDiv.appendChild(this._loadingTextDiv);
  27143. //set the predefined text
  27144. this._loadingTextDiv.innerHTML = this._loadingText;
  27145. // Loading img
  27146. var imgBack = new Image();
  27147. 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==";
  27148. imgBack.style.position = "absolute";
  27149. imgBack.style.left = "50%";
  27150. imgBack.style.top = "50%";
  27151. imgBack.style.marginLeft = "-50px";
  27152. imgBack.style.marginTop = "-50px";
  27153. imgBack.style.transition = "transform 1.0s ease";
  27154. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27155. var deg = 360;
  27156. var onTransitionEnd = function () {
  27157. deg += 360;
  27158. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27159. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27160. };
  27161. imgBack.addEventListener("transitionend", onTransitionEnd);
  27162. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27163. this._loadingDiv.appendChild(imgBack);
  27164. // front image
  27165. var imgFront = new Image();
  27166. 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=";
  27167. imgFront.style.position = "absolute";
  27168. imgFront.style.left = "50%";
  27169. imgFront.style.top = "50%";
  27170. imgFront.style.marginLeft = "-50px";
  27171. imgFront.style.marginTop = "-50px";
  27172. this._loadingDiv.appendChild(imgFront);
  27173. this._resizeLoadingUI();
  27174. window.addEventListener("resize", this._resizeLoadingUI);
  27175. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27176. document.body.appendChild(this._loadingDiv);
  27177. setTimeout(function () {
  27178. _this._loadingDiv.style.opacity = "1";
  27179. imgBack.style.transform = "rotateZ(360deg)";
  27180. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27181. }, 0);
  27182. };
  27183. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27184. var _this = this;
  27185. if (!this._loadingDiv) {
  27186. return;
  27187. }
  27188. var onTransitionEnd = function () {
  27189. if (!_this._loadingDiv) {
  27190. return;
  27191. }
  27192. document.body.removeChild(_this._loadingDiv);
  27193. window.removeEventListener("resize", _this._resizeLoadingUI);
  27194. _this._loadingDiv = null;
  27195. };
  27196. this._loadingDiv.style.opacity = "0";
  27197. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27198. };
  27199. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27200. set: function (text) {
  27201. this._loadingText = text;
  27202. if (this._loadingTextDiv) {
  27203. this._loadingTextDiv.innerHTML = this._loadingText;
  27204. }
  27205. },
  27206. enumerable: true,
  27207. configurable: true
  27208. });
  27209. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27210. get: function () {
  27211. return this._loadingDivBackgroundColor;
  27212. },
  27213. set: function (color) {
  27214. this._loadingDivBackgroundColor = color;
  27215. if (!this._loadingDiv) {
  27216. return;
  27217. }
  27218. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27219. },
  27220. enumerable: true,
  27221. configurable: true
  27222. });
  27223. return DefaultLoadingScreen;
  27224. })();
  27225. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27226. })(BABYLON || (BABYLON = {}));
  27227. var BABYLON;
  27228. (function (BABYLON) {
  27229. var SIMDVector3 = (function () {
  27230. function SIMDVector3() {
  27231. }
  27232. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27233. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27234. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27235. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27236. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27237. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27238. 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));
  27239. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27240. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27241. };
  27242. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27243. var v0 = SIMD.float32x4.splat(x);
  27244. var v1 = SIMD.float32x4.splat(y);
  27245. var v2 = SIMD.float32x4.splat(z);
  27246. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27247. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27248. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27249. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27250. 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));
  27251. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27252. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27253. };
  27254. return SIMDVector3;
  27255. })();
  27256. BABYLON.SIMDVector3 = SIMDVector3;
  27257. var SIMDMatrix = (function () {
  27258. function SIMDMatrix() {
  27259. }
  27260. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27261. if (offset === void 0) { offset = 0; }
  27262. var tm = this.m;
  27263. var om = other.m;
  27264. var om0 = SIMD.float32x4.load(om, 0);
  27265. var om1 = SIMD.float32x4.load(om, 4);
  27266. var om2 = SIMD.float32x4.load(om, 8);
  27267. var om3 = SIMD.float32x4.load(om, 12);
  27268. var tm0 = SIMD.float32x4.load(tm, 0);
  27269. 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)))));
  27270. var tm1 = SIMD.float32x4.load(tm, 4);
  27271. 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)))));
  27272. var tm2 = SIMD.float32x4.load(tm, 8);
  27273. 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)))));
  27274. var tm3 = SIMD.float32x4.load(tm, 12);
  27275. 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)))));
  27276. };
  27277. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27278. var src = this.m;
  27279. var dest = other.m;
  27280. var row0, row1, row2, row3;
  27281. var tmp1;
  27282. var minor0, minor1, minor2, minor3;
  27283. var det;
  27284. // Load the 4 rows
  27285. var src0 = SIMD.float32x4.load(src, 0);
  27286. var src1 = SIMD.float32x4.load(src, 4);
  27287. var src2 = SIMD.float32x4.load(src, 8);
  27288. var src3 = SIMD.float32x4.load(src, 12);
  27289. // Transpose the source matrix. Sort of. Not a true transpose operation
  27290. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27291. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27292. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27293. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27294. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27295. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27296. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27297. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27298. // This is a true transposition, but it will lead to an incorrect result
  27299. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27300. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27301. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27302. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27303. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27304. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27305. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27306. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27307. // ----
  27308. tmp1 = SIMD.float32x4.mul(row2, row3);
  27309. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27310. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27311. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27312. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27313. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27314. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27315. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27316. // ----
  27317. tmp1 = SIMD.float32x4.mul(row1, row2);
  27318. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27319. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27320. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27321. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27322. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27323. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27324. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27325. // ----
  27326. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27327. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27328. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27329. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27330. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27331. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27332. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27333. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27334. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27335. // ----
  27336. tmp1 = SIMD.float32x4.mul(row0, row1);
  27337. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27338. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27339. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27340. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27341. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27342. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27343. // ----
  27344. tmp1 = SIMD.float32x4.mul(row0, row3);
  27345. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27346. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27347. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27348. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27349. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27350. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27351. // ----
  27352. tmp1 = SIMD.float32x4.mul(row0, row2);
  27353. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27354. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27355. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27356. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27357. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27358. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27359. // Compute determinant
  27360. det = SIMD.float32x4.mul(row0, minor0);
  27361. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27362. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27363. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27364. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27365. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27366. // These shuffles aren't necessary if the faulty transposition is done
  27367. // up at the top of this function.
  27368. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27369. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27370. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27371. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27372. // Compute final values by multiplying with 1/det
  27373. minor0 = SIMD.float32x4.mul(det, minor0);
  27374. minor1 = SIMD.float32x4.mul(det, minor1);
  27375. minor2 = SIMD.float32x4.mul(det, minor2);
  27376. minor3 = SIMD.float32x4.mul(det, minor3);
  27377. SIMD.float32x4.store(dest, 0, minor0);
  27378. SIMD.float32x4.store(dest, 4, minor1);
  27379. SIMD.float32x4.store(dest, 8, minor2);
  27380. SIMD.float32x4.store(dest, 12, minor3);
  27381. return this;
  27382. };
  27383. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27384. var out = result.m;
  27385. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27386. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27387. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27388. // cc.kmVec3Subtract(f, pCenter, pEye);
  27389. var f = SIMD.float32x4.sub(center, eye);
  27390. // cc.kmVec3Normalize(f, f);
  27391. var tmp = SIMD.float32x4.mul(f, f);
  27392. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27393. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27394. // cc.kmVec3Assign(up, pUp);
  27395. // cc.kmVec3Normalize(up, up);
  27396. tmp = SIMD.float32x4.mul(up, up);
  27397. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27398. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27399. // cc.kmVec3Cross(s, f, up);
  27400. 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)));
  27401. // cc.kmVec3Normalize(s, s);
  27402. tmp = SIMD.float32x4.mul(s, s);
  27403. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27404. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27405. // cc.kmVec3Cross(u, s, f);
  27406. 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)));
  27407. // cc.kmVec3Normalize(s, s);
  27408. tmp = SIMD.float32x4.mul(s, s);
  27409. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27410. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27411. var zero = SIMD.float32x4.splat(0.0);
  27412. s = SIMD.float32x4.neg(s);
  27413. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27414. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27415. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27416. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27417. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27418. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27419. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27420. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27421. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27422. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27423. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27424. var b3 = SIMD.float32x4.neg(eye);
  27425. b3 = SIMD.float32x4.withW(b3, 1.0);
  27426. 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)))));
  27427. 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)))));
  27428. 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)))));
  27429. 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)))));
  27430. };
  27431. return SIMDMatrix;
  27432. })();
  27433. BABYLON.SIMDMatrix = SIMDMatrix;
  27434. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27435. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27436. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27437. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27438. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27439. var SIMDHelper = (function () {
  27440. function SIMDHelper() {
  27441. }
  27442. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27443. get: function () {
  27444. return SIMDHelper._isEnabled;
  27445. },
  27446. enumerable: true,
  27447. configurable: true
  27448. });
  27449. SIMDHelper.DisableSIMD = function () {
  27450. // Replace functions
  27451. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27452. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27453. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27454. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27455. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27456. SIMDHelper._isEnabled = false;
  27457. };
  27458. SIMDHelper.EnableSIMD = function () {
  27459. if (window.SIMD === undefined) {
  27460. return;
  27461. }
  27462. // Replace functions
  27463. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27464. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27465. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27466. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27468. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27469. get: function () { return this._data[0]; },
  27470. set: function (value) {
  27471. if (!this._data) {
  27472. this._data = new Float32Array(3);
  27473. }
  27474. this._data[0] = value;
  27475. }
  27476. });
  27477. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27478. get: function () { return this._data[1]; },
  27479. set: function (value) {
  27480. this._data[1] = value;
  27481. }
  27482. });
  27483. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27484. get: function () { return this._data[2]; },
  27485. set: function (value) {
  27486. this._data[2] = value;
  27487. }
  27488. });
  27489. SIMDHelper._isEnabled = true;
  27490. };
  27491. SIMDHelper._isEnabled = false;
  27492. return SIMDHelper;
  27493. })();
  27494. BABYLON.SIMDHelper = SIMDHelper;
  27495. })(BABYLON || (BABYLON = {}));
  27496. var BABYLON;
  27497. (function (BABYLON) {
  27498. var ShaderMaterial = (function (_super) {
  27499. __extends(ShaderMaterial, _super);
  27500. function ShaderMaterial(name, scene, shaderPath, options) {
  27501. _super.call(this, name, scene);
  27502. this._textures = new Array();
  27503. this._floats = new Array();
  27504. this._floatsArrays = {};
  27505. this._colors3 = new Array();
  27506. this._colors4 = new Array();
  27507. this._vectors2 = new Array();
  27508. this._vectors3 = new Array();
  27509. this._vectors4 = new Array();
  27510. this._matrices = new Array();
  27511. this._matrices3x3 = new Array();
  27512. this._matrices2x2 = new Array();
  27513. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27514. this._shaderPath = shaderPath;
  27515. options.needAlphaBlending = options.needAlphaBlending || false;
  27516. options.needAlphaTesting = options.needAlphaTesting || false;
  27517. options.attributes = options.attributes || ["position", "normal", "uv"];
  27518. options.uniforms = options.uniforms || ["worldViewProjection"];
  27519. options.samplers = options.samplers || [];
  27520. options.defines = options.defines || [];
  27521. this._options = options;
  27522. }
  27523. ShaderMaterial.prototype.needAlphaBlending = function () {
  27524. return this._options.needAlphaBlending;
  27525. };
  27526. ShaderMaterial.prototype.needAlphaTesting = function () {
  27527. return this._options.needAlphaTesting;
  27528. };
  27529. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27530. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27531. this._options.uniforms.push(uniformName);
  27532. }
  27533. };
  27534. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27535. if (this._options.samplers.indexOf(name) === -1) {
  27536. this._options.samplers.push(name);
  27537. }
  27538. this._textures[name] = texture;
  27539. return this;
  27540. };
  27541. ShaderMaterial.prototype.setFloat = function (name, value) {
  27542. this._checkUniform(name);
  27543. this._floats[name] = value;
  27544. return this;
  27545. };
  27546. ShaderMaterial.prototype.setFloats = function (name, value) {
  27547. this._checkUniform(name);
  27548. this._floatsArrays[name] = value;
  27549. return this;
  27550. };
  27551. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27552. this._checkUniform(name);
  27553. this._colors3[name] = value;
  27554. return this;
  27555. };
  27556. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27557. this._checkUniform(name);
  27558. this._colors4[name] = value;
  27559. return this;
  27560. };
  27561. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27562. this._checkUniform(name);
  27563. this._vectors2[name] = value;
  27564. return this;
  27565. };
  27566. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27567. this._checkUniform(name);
  27568. this._vectors3[name] = value;
  27569. return this;
  27570. };
  27571. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27572. this._checkUniform(name);
  27573. this._vectors4[name] = value;
  27574. return this;
  27575. };
  27576. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27577. this._checkUniform(name);
  27578. this._matrices[name] = value;
  27579. return this;
  27580. };
  27581. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27582. this._checkUniform(name);
  27583. this._matrices3x3[name] = value;
  27584. return this;
  27585. };
  27586. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27587. this._checkUniform(name);
  27588. this._matrices2x2[name] = value;
  27589. return this;
  27590. };
  27591. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27592. var scene = this.getScene();
  27593. var engine = scene.getEngine();
  27594. if (!this.checkReadyOnEveryCall) {
  27595. if (this._renderId === scene.getRenderId()) {
  27596. return true;
  27597. }
  27598. }
  27599. // Instances
  27600. var defines = [];
  27601. var fallbacks = new BABYLON.EffectFallbacks();
  27602. if (useInstances) {
  27603. defines.push("#define INSTANCES");
  27604. }
  27605. for (var index = 0; index < this._options.defines.length; index++) {
  27606. defines.push(this._options.defines[index]);
  27607. }
  27608. // Bones
  27609. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27610. defines.push("#define BONES");
  27611. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27612. defines.push("#define BONES4");
  27613. fallbacks.addFallback(0, "BONES4");
  27614. }
  27615. // Alpha test
  27616. if (engine.getAlphaTesting()) {
  27617. defines.push("#define ALPHATEST");
  27618. }
  27619. var previousEffect = this._effect;
  27620. var join = defines.join("\n");
  27621. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27622. if (!this._effect.isReady()) {
  27623. return false;
  27624. }
  27625. if (previousEffect !== this._effect) {
  27626. scene.resetCachedMaterial();
  27627. }
  27628. this._renderId = scene.getRenderId();
  27629. return true;
  27630. };
  27631. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27632. var scene = this.getScene();
  27633. if (this._options.uniforms.indexOf("world") !== -1) {
  27634. this._effect.setMatrix("world", world);
  27635. }
  27636. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27637. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27638. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27639. }
  27640. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27641. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27642. }
  27643. };
  27644. ShaderMaterial.prototype.bind = function (world, mesh) {
  27645. // Std values
  27646. this.bindOnlyWorldMatrix(world);
  27647. if (this.getScene().getCachedMaterial() !== this) {
  27648. if (this._options.uniforms.indexOf("view") !== -1) {
  27649. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27650. }
  27651. if (this._options.uniforms.indexOf("projection") !== -1) {
  27652. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27653. }
  27654. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27655. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27656. }
  27657. // Bones
  27658. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27659. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27660. }
  27661. // Texture
  27662. for (var name in this._textures) {
  27663. this._effect.setTexture(name, this._textures[name]);
  27664. }
  27665. // Float
  27666. for (name in this._floats) {
  27667. this._effect.setFloat(name, this._floats[name]);
  27668. }
  27669. // Float s
  27670. for (name in this._floatsArrays) {
  27671. this._effect.setArray(name, this._floatsArrays[name]);
  27672. }
  27673. // Color3
  27674. for (name in this._colors3) {
  27675. this._effect.setColor3(name, this._colors3[name]);
  27676. }
  27677. // Color4
  27678. for (name in this._colors4) {
  27679. var color = this._colors4[name];
  27680. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27681. }
  27682. // Vector2
  27683. for (name in this._vectors2) {
  27684. this._effect.setVector2(name, this._vectors2[name]);
  27685. }
  27686. // Vector3
  27687. for (name in this._vectors3) {
  27688. this._effect.setVector3(name, this._vectors3[name]);
  27689. }
  27690. // Vector4
  27691. for (name in this._vectors4) {
  27692. this._effect.setVector4(name, this._vectors4[name]);
  27693. }
  27694. // Matrix
  27695. for (name in this._matrices) {
  27696. this._effect.setMatrix(name, this._matrices[name]);
  27697. }
  27698. // Matrix 3x3
  27699. for (name in this._matrices3x3) {
  27700. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27701. }
  27702. // Matrix 2x2
  27703. for (name in this._matrices2x2) {
  27704. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27705. }
  27706. }
  27707. _super.prototype.bind.call(this, world, mesh);
  27708. };
  27709. ShaderMaterial.prototype.clone = function (name) {
  27710. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27711. return newShaderMaterial;
  27712. };
  27713. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27714. for (var name in this._textures) {
  27715. this._textures[name].dispose();
  27716. }
  27717. this._textures = [];
  27718. _super.prototype.dispose.call(this, forceDisposeEffect);
  27719. };
  27720. return ShaderMaterial;
  27721. })(BABYLON.Material);
  27722. BABYLON.ShaderMaterial = ShaderMaterial;
  27723. })(BABYLON || (BABYLON = {}));
  27724. var BABYLON;
  27725. (function (BABYLON) {
  27726. var Internals;
  27727. (function (Internals) {
  27728. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27729. // All values and structures referenced from:
  27730. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27731. var DDS_MAGIC = 0x20534444;
  27732. 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;
  27733. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27734. 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;
  27735. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27736. function FourCCToInt32(value) {
  27737. return value.charCodeAt(0) +
  27738. (value.charCodeAt(1) << 8) +
  27739. (value.charCodeAt(2) << 16) +
  27740. (value.charCodeAt(3) << 24);
  27741. }
  27742. function Int32ToFourCC(value) {
  27743. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27744. }
  27745. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27746. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27747. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27748. var headerLengthInt = 31; // The header length in 32 bit ints
  27749. // Offsets into the header array
  27750. var off_magic = 0;
  27751. var off_size = 1;
  27752. var off_flags = 2;
  27753. var off_height = 3;
  27754. var off_width = 4;
  27755. var off_mipmapCount = 7;
  27756. var off_pfFlags = 20;
  27757. var off_pfFourCC = 21;
  27758. var off_RGBbpp = 22;
  27759. var off_RMask = 23;
  27760. var off_GMask = 24;
  27761. var off_BMask = 25;
  27762. var off_AMask = 26;
  27763. var off_caps1 = 27;
  27764. var off_caps2 = 28;
  27765. ;
  27766. var DDSTools = (function () {
  27767. function DDSTools() {
  27768. }
  27769. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27770. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27771. var mipmapCount = 1;
  27772. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27773. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27774. }
  27775. return {
  27776. width: header[off_width],
  27777. height: header[off_height],
  27778. mipmapCount: mipmapCount,
  27779. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27780. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27781. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27782. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27783. };
  27784. };
  27785. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27786. var byteArray = new Uint8Array(dataLength);
  27787. var srcData = new Uint8Array(arrayBuffer);
  27788. var index = 0;
  27789. for (var y = height - 1; y >= 0; y--) {
  27790. for (var x = 0; x < width; x++) {
  27791. var srcPos = dataOffset + (x + y * width) * 4;
  27792. byteArray[index + 2] = srcData[srcPos];
  27793. byteArray[index + 1] = srcData[srcPos + 1];
  27794. byteArray[index] = srcData[srcPos + 2];
  27795. byteArray[index + 3] = srcData[srcPos + 3];
  27796. index += 4;
  27797. }
  27798. }
  27799. return byteArray;
  27800. };
  27801. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27802. var byteArray = new Uint8Array(dataLength);
  27803. var srcData = new Uint8Array(arrayBuffer);
  27804. var index = 0;
  27805. for (var y = height - 1; y >= 0; y--) {
  27806. for (var x = 0; x < width; x++) {
  27807. var srcPos = dataOffset + (x + y * width) * 3;
  27808. byteArray[index + 2] = srcData[srcPos];
  27809. byteArray[index + 1] = srcData[srcPos + 1];
  27810. byteArray[index] = srcData[srcPos + 2];
  27811. index += 3;
  27812. }
  27813. }
  27814. return byteArray;
  27815. };
  27816. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27817. var byteArray = new Uint8Array(dataLength);
  27818. var srcData = new Uint8Array(arrayBuffer);
  27819. var index = 0;
  27820. for (var y = height - 1; y >= 0; y--) {
  27821. for (var x = 0; x < width; x++) {
  27822. var srcPos = dataOffset + (x + y * width);
  27823. byteArray[index] = srcData[srcPos];
  27824. index++;
  27825. }
  27826. }
  27827. return byteArray;
  27828. };
  27829. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27830. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27831. if (header[off_magic] != DDS_MAGIC) {
  27832. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27833. return;
  27834. }
  27835. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27836. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27837. return;
  27838. }
  27839. if (info.isFourCC) {
  27840. fourCC = header[off_pfFourCC];
  27841. switch (fourCC) {
  27842. case FOURCC_DXT1:
  27843. blockBytes = 8;
  27844. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27845. break;
  27846. case FOURCC_DXT3:
  27847. blockBytes = 16;
  27848. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27849. break;
  27850. case FOURCC_DXT5:
  27851. blockBytes = 16;
  27852. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27853. break;
  27854. default:
  27855. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27856. return;
  27857. }
  27858. }
  27859. mipmapCount = 1;
  27860. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27861. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27862. }
  27863. var bpp = header[off_RGBbpp];
  27864. for (var face = 0; face < faces; face++) {
  27865. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27866. width = header[off_width];
  27867. height = header[off_height];
  27868. dataOffset = header[off_size] + 4;
  27869. for (i = 0; i < mipmapCount; ++i) {
  27870. if (info.isRGB) {
  27871. if (bpp === 24) {
  27872. dataLength = width * height * 3;
  27873. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27874. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27875. }
  27876. else {
  27877. dataLength = width * height * 4;
  27878. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27879. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27880. }
  27881. }
  27882. else if (info.isLuminance) {
  27883. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27884. var unpaddedRowSize = width;
  27885. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27886. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27887. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27888. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27889. }
  27890. else {
  27891. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27892. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27893. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27894. }
  27895. dataOffset += dataLength;
  27896. width *= 0.5;
  27897. height *= 0.5;
  27898. width = Math.max(1.0, width);
  27899. height = Math.max(1.0, height);
  27900. }
  27901. }
  27902. };
  27903. return DDSTools;
  27904. })();
  27905. Internals.DDSTools = DDSTools;
  27906. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27907. })(BABYLON || (BABYLON = {}));
  27908. var BABYLON;
  27909. (function (BABYLON) {
  27910. var CannonJSPlugin = (function () {
  27911. function CannonJSPlugin() {
  27912. this._registeredMeshes = [];
  27913. this._physicsMaterials = [];
  27914. this.updateBodyPosition = function (mesh) {
  27915. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27916. var registeredMesh = this._registeredMeshes[index];
  27917. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27918. var body = registeredMesh.body;
  27919. var center = mesh.getBoundingInfo().boundingBox.center;
  27920. body.position.set(center.x, center.y, center.z);
  27921. body.quaternion.copy(mesh.rotationQuaternion);
  27922. if (registeredMesh.deltaRotation) {
  27923. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27924. body.quaternion = body.quaternion.mult(tmpQ);
  27925. }
  27926. if (registeredMesh.heightmap) {
  27927. //calculate the correct body position:
  27928. var rotationQuaternion = mesh.rotationQuaternion;
  27929. mesh.rotationQuaternion = new BABYLON.Quaternion();
  27930. mesh.computeWorldMatrix(true);
  27931. //get original center with no rotation
  27932. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  27933. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  27934. //rotation is back
  27935. mesh.rotationQuaternion = rotationQuaternion;
  27936. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  27937. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  27938. mesh.setPivotMatrix(p);
  27939. mesh.computeWorldMatrix(true);
  27940. //calculate the translation
  27941. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  27942. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  27943. //add it inverted to the delta
  27944. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  27945. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  27946. mesh.setPivotMatrix(oldPivot);
  27947. mesh.computeWorldMatrix(true);
  27948. }
  27949. return;
  27950. }
  27951. }
  27952. };
  27953. }
  27954. CannonJSPlugin.prototype.initialize = function (iterations) {
  27955. if (iterations === void 0) { iterations = 10; }
  27956. this._world = new CANNON.World();
  27957. this._world.broadphase = new CANNON.NaiveBroadphase();
  27958. this._world.solver.iterations = iterations;
  27959. };
  27960. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  27961. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27962. };
  27963. CannonJSPlugin.prototype.runOneStep = function (delta) {
  27964. this._world.step(delta);
  27965. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27966. var registeredMesh = this._registeredMeshes[index];
  27967. if (registeredMesh.isChild) {
  27968. continue;
  27969. }
  27970. // Body position
  27971. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  27972. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  27973. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  27974. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  27975. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  27976. if (registeredMesh.deltaRotation) {
  27977. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  27978. }
  27979. }
  27980. };
  27981. CannonJSPlugin.prototype.setGravity = function (gravity) {
  27982. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  27983. };
  27984. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27985. this.unregisterMesh(mesh);
  27986. if (!mesh.rotationQuaternion) {
  27987. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27988. }
  27989. mesh.computeWorldMatrix(true);
  27990. var shape = this._createShape(mesh, impostor);
  27991. return this._createRigidBodyFromShape(shape, mesh, options);
  27992. };
  27993. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  27994. //get the correct bounding box
  27995. var oldQuaternion = mesh.rotationQuaternion;
  27996. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27997. mesh.computeWorldMatrix(true);
  27998. var returnValue;
  27999. switch (impostor) {
  28000. case BABYLON.PhysicsEngine.SphereImpostor:
  28001. var bbox = mesh.getBoundingInfo().boundingBox;
  28002. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28003. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28004. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28005. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28006. break;
  28007. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28008. case BABYLON.PhysicsEngine.CylinderImpostor:
  28009. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28010. case BABYLON.PhysicsEngine.BoxImpostor:
  28011. bbox = mesh.getBoundingInfo().boundingBox;
  28012. var min = bbox.minimumWorld;
  28013. var max = bbox.maximumWorld;
  28014. var box = max.subtract(min).scale(0.5);
  28015. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28016. break;
  28017. case BABYLON.PhysicsEngine.PlaneImpostor:
  28018. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28019. returnValue = new CANNON.Plane();
  28020. break;
  28021. case BABYLON.PhysicsEngine.MeshImpostor:
  28022. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28023. var rawFaces = mesh.getIndices();
  28024. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28025. break;
  28026. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28027. returnValue = this._createHeightmap(mesh);
  28028. break;
  28029. }
  28030. mesh.rotationQuaternion = oldQuaternion;
  28031. return returnValue;
  28032. };
  28033. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28034. var verts = [], faces = [];
  28035. mesh.computeWorldMatrix(true);
  28036. //reuse this variable
  28037. var transformed = BABYLON.Vector3.Zero();
  28038. // Get vertices
  28039. for (var i = 0; i < rawVerts.length; i += 3) {
  28040. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28041. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28042. }
  28043. // Get faces
  28044. for (var j = 0; j < rawFaces.length; j += 3) {
  28045. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28046. }
  28047. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28048. return shape;
  28049. };
  28050. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28051. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28052. var matrix = [];
  28053. //For now pointDepth will not be used and will be automatically calculated.
  28054. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28055. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28056. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28057. var elementSize = dim * 2 / arraySize;
  28058. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28059. for (var i = 0; i < pos.length; i = i + 3) {
  28060. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28061. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28062. var y = pos[i + 1] + minY;
  28063. if (!matrix[x]) {
  28064. matrix[x] = [];
  28065. }
  28066. if (!matrix[x][z]) {
  28067. matrix[x][z] = y;
  28068. }
  28069. matrix[x][z] = Math.max(y, matrix[x][z]);
  28070. }
  28071. for (var x = 0; x <= arraySize; ++x) {
  28072. if (!matrix[x]) {
  28073. var loc = 1;
  28074. while (!matrix[(x + loc) % arraySize]) {
  28075. loc++;
  28076. }
  28077. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28078. }
  28079. for (var z = 0; z <= arraySize; ++z) {
  28080. if (!matrix[x][z]) {
  28081. var loc = 1;
  28082. var newValue;
  28083. while (newValue === undefined) {
  28084. newValue = matrix[x][(z + loc++) % arraySize];
  28085. }
  28086. matrix[x][z] = newValue;
  28087. }
  28088. }
  28089. }
  28090. var shape = new CANNON.Heightfield(matrix, {
  28091. elementSize: elementSize
  28092. });
  28093. //For future reference, needed for body transformation
  28094. shape.minY = minY;
  28095. return shape;
  28096. };
  28097. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28098. var index;
  28099. var mat;
  28100. for (index = 0; index < this._physicsMaterials.length; index++) {
  28101. mat = this._physicsMaterials[index];
  28102. if (mat.friction === friction && mat.restitution === restitution) {
  28103. return mat;
  28104. }
  28105. }
  28106. var currentMat = new CANNON.Material("mat");
  28107. this._physicsMaterials.push(currentMat);
  28108. for (index = 0; index < this._physicsMaterials.length; index++) {
  28109. mat = this._physicsMaterials[index];
  28110. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28111. this._world.addContactMaterial(contactMaterial);
  28112. }
  28113. return currentMat;
  28114. };
  28115. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28116. if (!mesh.rotationQuaternion) {
  28117. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28118. }
  28119. // The delta between the mesh position and the mesh bounding box center
  28120. var bbox = mesh.getBoundingInfo().boundingBox;
  28121. var deltaPosition = mesh.position.subtract(bbox.center);
  28122. var deltaRotation;
  28123. var material = this._addMaterial(options.friction, options.restitution);
  28124. var body = new CANNON.Body({
  28125. mass: options.mass,
  28126. material: material,
  28127. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28128. });
  28129. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28130. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28131. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28132. //-90 DEG in X, precalculated
  28133. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28134. body.quaternion = body.quaternion.mult(tmpQ);
  28135. //Invert! (Precalculated, 90 deg in X)
  28136. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28137. }
  28138. //If it is a heightfield, if should be centered.
  28139. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28140. //calculate the correct body position:
  28141. var rotationQuaternion = mesh.rotationQuaternion;
  28142. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28143. mesh.computeWorldMatrix(true);
  28144. //get original center with no rotation
  28145. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28146. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28147. //rotation is back
  28148. mesh.rotationQuaternion = rotationQuaternion;
  28149. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28150. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28151. mesh.setPivotMatrix(p);
  28152. mesh.computeWorldMatrix(true);
  28153. //calculate the translation
  28154. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28155. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28156. //add it inverted to the delta
  28157. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28158. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28159. mesh.setPivotMatrix(oldPivot);
  28160. mesh.computeWorldMatrix(true);
  28161. }
  28162. //add the shape
  28163. body.addShape(shape);
  28164. this._world.add(body);
  28165. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28166. return body;
  28167. };
  28168. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28169. var initialMesh = parts[0].mesh;
  28170. this.unregisterMesh(initialMesh);
  28171. initialMesh.computeWorldMatrix(true);
  28172. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28173. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28174. for (var index = 1; index < parts.length; index++) {
  28175. var mesh = parts[index].mesh;
  28176. mesh.computeWorldMatrix(true);
  28177. var shape = this._createShape(mesh, parts[index].impostor);
  28178. var localPosition = mesh.position;
  28179. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28180. }
  28181. return body;
  28182. };
  28183. CannonJSPlugin.prototype._unbindBody = function (body) {
  28184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28185. var registeredMesh = this._registeredMeshes[index];
  28186. if (registeredMesh.body === body) {
  28187. this._world.remove(registeredMesh.body);
  28188. registeredMesh.body = null;
  28189. registeredMesh.delta = null;
  28190. registeredMesh.deltaRotation = null;
  28191. }
  28192. }
  28193. };
  28194. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28195. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28196. var registeredMesh = this._registeredMeshes[index];
  28197. if (registeredMesh.mesh === mesh) {
  28198. // Remove body
  28199. if (registeredMesh.body) {
  28200. this._unbindBody(registeredMesh.body);
  28201. }
  28202. this._registeredMeshes.splice(index, 1);
  28203. return;
  28204. }
  28205. }
  28206. };
  28207. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28208. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28209. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28210. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28211. var registeredMesh = this._registeredMeshes[index];
  28212. if (registeredMesh.mesh === mesh) {
  28213. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28214. return;
  28215. }
  28216. }
  28217. };
  28218. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28219. var body1 = null, body2 = null;
  28220. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28221. var registeredMesh = this._registeredMeshes[index];
  28222. if (registeredMesh.mesh === mesh1) {
  28223. body1 = registeredMesh.body;
  28224. }
  28225. else if (registeredMesh.mesh === mesh2) {
  28226. body2 = registeredMesh.body;
  28227. }
  28228. }
  28229. if (!body1 || !body2) {
  28230. return false;
  28231. }
  28232. 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));
  28233. this._world.addConstraint(constraint);
  28234. return true;
  28235. };
  28236. CannonJSPlugin.prototype.dispose = function () {
  28237. while (this._registeredMeshes.length) {
  28238. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28239. }
  28240. };
  28241. CannonJSPlugin.prototype.isSupported = function () {
  28242. return window.CANNON !== undefined;
  28243. };
  28244. CannonJSPlugin.prototype.getWorldObject = function () {
  28245. return this._world;
  28246. };
  28247. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28248. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28249. var registeredMesh = this._registeredMeshes[index];
  28250. if (registeredMesh.mesh === mesh) {
  28251. return registeredMesh.body;
  28252. }
  28253. }
  28254. return null;
  28255. };
  28256. return CannonJSPlugin;
  28257. })();
  28258. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28259. })(BABYLON || (BABYLON = {}));
  28260. var BABYLON;
  28261. (function (BABYLON) {
  28262. var OimoJSPlugin = (function () {
  28263. function OimoJSPlugin() {
  28264. this._registeredMeshes = [];
  28265. /**
  28266. * Update the body position according to the mesh position
  28267. * @param mesh
  28268. */
  28269. this.updateBodyPosition = function (mesh) {
  28270. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28271. var registeredMesh = this._registeredMeshes[index];
  28272. var body = registeredMesh.body.body;
  28273. var updated = false;
  28274. var newPosition;
  28275. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28276. mesh.computeWorldMatrix(true);
  28277. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28278. updated = true;
  28279. }
  28280. else if (registeredMesh.mesh.parent === mesh) {
  28281. mesh.computeWorldMatrix(true);
  28282. registeredMesh.mesh.computeWorldMatrix(true);
  28283. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28284. updated = true;
  28285. }
  28286. if (updated) {
  28287. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28288. body.setQuaternion(mesh.rotationQuaternion);
  28289. body.sleeping = false;
  28290. //force Oimo to update the body's position
  28291. body.updatePosition(1);
  28292. }
  28293. }
  28294. };
  28295. }
  28296. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28297. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28298. };
  28299. OimoJSPlugin.prototype.initialize = function (iterations) {
  28300. this._world = new OIMO.World(null, null, iterations);
  28301. this._world.clear();
  28302. };
  28303. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28304. this._world.gravity = gravity;
  28305. };
  28306. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28307. this.unregisterMesh(mesh);
  28308. if (!mesh.rotationQuaternion) {
  28309. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28310. }
  28311. mesh.computeWorldMatrix(true);
  28312. var bbox = mesh.getBoundingInfo().boundingBox;
  28313. // The delta between the mesh position and the mesh bounding box center
  28314. var deltaPosition = mesh.position.subtract(bbox.center);
  28315. //calculate rotation to fit Oimo's needs (Euler...)
  28316. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28317. //get the correct bounding box
  28318. var oldQuaternion = mesh.rotationQuaternion;
  28319. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28320. mesh.computeWorldMatrix(true);
  28321. var bodyConfig = {
  28322. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28323. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28324. move: options.mass != 0,
  28325. config: [options.mass, options.friction, options.restitution],
  28326. world: this._world
  28327. };
  28328. // register mesh
  28329. switch (impostor) {
  28330. case BABYLON.PhysicsEngine.SphereImpostor:
  28331. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28332. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28333. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28334. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28335. bodyConfig.type = 'sphere';
  28336. bodyConfig.size = [size];
  28337. break;
  28338. case BABYLON.PhysicsEngine.PlaneImpostor:
  28339. //Oimo "fakes" a cylinder as a box, so why don't we!
  28340. case BABYLON.PhysicsEngine.CylinderImpostor:
  28341. case BABYLON.PhysicsEngine.BoxImpostor:
  28342. var min = bbox.minimumWorld;
  28343. var max = bbox.maximumWorld;
  28344. var box = max.subtract(min);
  28345. var sizeX = this._checkWithEpsilon(box.x);
  28346. var sizeY = this._checkWithEpsilon(box.y);
  28347. var sizeZ = this._checkWithEpsilon(box.z);
  28348. bodyConfig.type = 'box';
  28349. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28350. break;
  28351. }
  28352. var body = new OIMO.Body(bodyConfig);
  28353. //We have to access the rigid body's properties to set the quaternion.
  28354. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28355. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28356. //TEST
  28357. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28358. //update the internal rotation matrix
  28359. //body.body.syncShapes();
  28360. this._registeredMeshes.push({
  28361. mesh: mesh,
  28362. body: body,
  28363. delta: deltaPosition
  28364. });
  28365. //for the sake of consistency.
  28366. mesh.rotationQuaternion = oldQuaternion;
  28367. return body;
  28368. };
  28369. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28370. var types = [], sizes = [], positions = [], rotations = [];
  28371. var initialMesh = parts[0].mesh;
  28372. for (var index = 0; index < parts.length; index++) {
  28373. var part = parts[index];
  28374. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28375. types.push(bodyParameters.type);
  28376. sizes.push.apply(sizes, bodyParameters.size);
  28377. positions.push.apply(positions, bodyParameters.pos);
  28378. rotations.push.apply(rotations, bodyParameters.rot);
  28379. }
  28380. var body = new OIMO.Body({
  28381. type: types,
  28382. size: sizes,
  28383. pos: positions,
  28384. rot: rotations,
  28385. move: options.mass != 0,
  28386. config: [options.mass, options.friction, options.restitution],
  28387. world: this._world
  28388. });
  28389. //Reset the body's rotation to be of the initial mesh's.
  28390. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28391. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28392. this._registeredMeshes.push({
  28393. mesh: initialMesh,
  28394. body: body
  28395. });
  28396. return body;
  28397. };
  28398. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28399. var mesh = part.mesh;
  28400. if (!mesh.rotationQuaternion) {
  28401. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28402. }
  28403. // We need the bounding box/sphere info to compute the physics body
  28404. mesh.computeWorldMatrix(true);
  28405. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28406. var bodyParameters = {
  28407. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28408. //A bug in Oimo (Body class) prevents us from using rot directly.
  28409. rot: [0, 0, 0],
  28410. //For future reference, if the bug will ever be fixed.
  28411. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28412. };
  28413. var oldQuaternion = mesh.rotationQuaternion;
  28414. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28415. mesh.computeWorldMatrix(true);
  28416. switch (part.impostor) {
  28417. case BABYLON.PhysicsEngine.SphereImpostor:
  28418. var bbox = mesh.getBoundingInfo().boundingBox;
  28419. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28420. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28421. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28422. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28423. bodyParameters.type = 'sphere';
  28424. bodyParameters.size = [size, size, size];
  28425. break;
  28426. case BABYLON.PhysicsEngine.PlaneImpostor:
  28427. case BABYLON.PhysicsEngine.CylinderImpostor:
  28428. case BABYLON.PhysicsEngine.BoxImpostor:
  28429. bbox = mesh.getBoundingInfo().boundingBox;
  28430. var min = bbox.minimumWorld;
  28431. var max = bbox.maximumWorld;
  28432. var box = max.subtract(min);
  28433. var sizeX = this._checkWithEpsilon(box.x);
  28434. var sizeY = this._checkWithEpsilon(box.y);
  28435. var sizeZ = this._checkWithEpsilon(box.z);
  28436. bodyParameters.type = 'box';
  28437. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28438. break;
  28439. }
  28440. mesh.rotationQuaternion = oldQuaternion;
  28441. return bodyParameters;
  28442. };
  28443. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28444. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28445. var registeredMesh = this._registeredMeshes[index];
  28446. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28447. if (registeredMesh.body) {
  28448. this._world.removeRigidBody(registeredMesh.body.body);
  28449. this._unbindBody(registeredMesh.body);
  28450. }
  28451. this._registeredMeshes.splice(index, 1);
  28452. return;
  28453. }
  28454. }
  28455. };
  28456. OimoJSPlugin.prototype._unbindBody = function (body) {
  28457. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28458. var registeredMesh = this._registeredMeshes[index];
  28459. if (registeredMesh.body === body) {
  28460. registeredMesh.body = null;
  28461. }
  28462. }
  28463. };
  28464. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28465. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28466. var registeredMesh = this._registeredMeshes[index];
  28467. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28468. // Get object mass to have a behaviour similar to cannon.js
  28469. var mass = registeredMesh.body.body.massInfo.mass;
  28470. // The force is scaled with the mass of object
  28471. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28472. return;
  28473. }
  28474. }
  28475. };
  28476. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28477. var body1 = null, body2 = null;
  28478. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28479. var registeredMesh = this._registeredMeshes[index];
  28480. if (registeredMesh.mesh === mesh1) {
  28481. body1 = registeredMesh.body.body;
  28482. }
  28483. else if (registeredMesh.mesh === mesh2) {
  28484. body2 = registeredMesh.body.body;
  28485. }
  28486. }
  28487. if (!body1 || !body2) {
  28488. return false;
  28489. }
  28490. if (!options) {
  28491. options = {};
  28492. }
  28493. new OIMO.Link({
  28494. type: options.type,
  28495. body1: body1,
  28496. body2: body2,
  28497. min: options.min,
  28498. max: options.max,
  28499. axe1: options.axe1,
  28500. axe2: options.axe2,
  28501. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28502. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28503. collision: options.collision,
  28504. spring: options.spring,
  28505. world: this._world
  28506. });
  28507. return true;
  28508. };
  28509. OimoJSPlugin.prototype.dispose = function () {
  28510. this._world.clear();
  28511. while (this._registeredMeshes.length) {
  28512. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28513. }
  28514. };
  28515. OimoJSPlugin.prototype.isSupported = function () {
  28516. return OIMO !== undefined;
  28517. };
  28518. OimoJSPlugin.prototype.getWorldObject = function () {
  28519. return this._world;
  28520. };
  28521. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28522. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28523. var registeredMesh = this._registeredMeshes[index];
  28524. if (registeredMesh.mesh === mesh) {
  28525. return registeredMesh.body;
  28526. }
  28527. }
  28528. return null;
  28529. };
  28530. OimoJSPlugin.prototype._getLastShape = function (body) {
  28531. var lastShape = body.shapes;
  28532. while (lastShape.next) {
  28533. lastShape = lastShape.next;
  28534. }
  28535. return lastShape;
  28536. };
  28537. OimoJSPlugin.prototype.runOneStep = function (time) {
  28538. this._world.step();
  28539. // Update the position of all registered meshes
  28540. var i = this._registeredMeshes.length;
  28541. var m;
  28542. while (i--) {
  28543. var body = this._registeredMeshes[i].body.body;
  28544. var mesh = this._registeredMeshes[i].mesh;
  28545. if (!this._registeredMeshes[i].delta) {
  28546. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28547. }
  28548. if (!body.sleeping) {
  28549. //TODO check that
  28550. if (body.shapes.next) {
  28551. var parentShape = this._getLastShape(body);
  28552. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28553. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28554. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28555. }
  28556. else {
  28557. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28558. }
  28559. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28560. mesh.computeWorldMatrix();
  28561. }
  28562. }
  28563. };
  28564. return OimoJSPlugin;
  28565. })();
  28566. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28567. })(BABYLON || (BABYLON = {}));
  28568. var BABYLON;
  28569. (function (BABYLON) {
  28570. var DisplayPassPostProcess = (function (_super) {
  28571. __extends(DisplayPassPostProcess, _super);
  28572. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28573. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28574. }
  28575. return DisplayPassPostProcess;
  28576. })(BABYLON.PostProcess);
  28577. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28578. })(BABYLON || (BABYLON = {}));
  28579. var BABYLON;
  28580. (function (BABYLON) {
  28581. var SimplificationSettings = (function () {
  28582. function SimplificationSettings(quality, distance, optimizeMesh) {
  28583. this.quality = quality;
  28584. this.distance = distance;
  28585. this.optimizeMesh = optimizeMesh;
  28586. }
  28587. return SimplificationSettings;
  28588. })();
  28589. BABYLON.SimplificationSettings = SimplificationSettings;
  28590. var SimplificationQueue = (function () {
  28591. function SimplificationQueue() {
  28592. this.running = false;
  28593. this._simplificationArray = [];
  28594. }
  28595. SimplificationQueue.prototype.addTask = function (task) {
  28596. this._simplificationArray.push(task);
  28597. };
  28598. SimplificationQueue.prototype.executeNext = function () {
  28599. var task = this._simplificationArray.pop();
  28600. if (task) {
  28601. this.running = true;
  28602. this.runSimplification(task);
  28603. }
  28604. else {
  28605. this.running = false;
  28606. }
  28607. };
  28608. SimplificationQueue.prototype.runSimplification = function (task) {
  28609. var _this = this;
  28610. if (task.parallelProcessing) {
  28611. //parallel simplifier
  28612. task.settings.forEach(function (setting) {
  28613. var simplifier = _this.getSimplifier(task);
  28614. simplifier.simplify(setting, function (newMesh) {
  28615. task.mesh.addLODLevel(setting.distance, newMesh);
  28616. newMesh.isVisible = true;
  28617. //check if it is the last
  28618. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28619. //all done, run the success callback.
  28620. task.successCallback();
  28621. }
  28622. _this.executeNext();
  28623. });
  28624. });
  28625. }
  28626. else {
  28627. //single simplifier.
  28628. var simplifier = this.getSimplifier(task);
  28629. var runDecimation = function (setting, callback) {
  28630. simplifier.simplify(setting, function (newMesh) {
  28631. task.mesh.addLODLevel(setting.distance, newMesh);
  28632. newMesh.isVisible = true;
  28633. //run the next quality level
  28634. callback();
  28635. });
  28636. };
  28637. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28638. runDecimation(task.settings[loop.index], function () {
  28639. loop.executeNext();
  28640. });
  28641. }, function () {
  28642. //execution ended, run the success callback.
  28643. if (task.successCallback) {
  28644. task.successCallback();
  28645. }
  28646. _this.executeNext();
  28647. });
  28648. }
  28649. };
  28650. SimplificationQueue.prototype.getSimplifier = function (task) {
  28651. switch (task.simplificationType) {
  28652. case SimplificationType.QUADRATIC:
  28653. default:
  28654. return new QuadraticErrorSimplification(task.mesh);
  28655. }
  28656. };
  28657. return SimplificationQueue;
  28658. })();
  28659. BABYLON.SimplificationQueue = SimplificationQueue;
  28660. /**
  28661. * The implemented types of simplification.
  28662. * At the moment only Quadratic Error Decimation is implemented.
  28663. */
  28664. (function (SimplificationType) {
  28665. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28666. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28667. var SimplificationType = BABYLON.SimplificationType;
  28668. var DecimationTriangle = (function () {
  28669. function DecimationTriangle(vertices) {
  28670. this.vertices = vertices;
  28671. this.error = new Array(4);
  28672. this.deleted = false;
  28673. this.isDirty = false;
  28674. this.deletePending = false;
  28675. this.borderFactor = 0;
  28676. }
  28677. return DecimationTriangle;
  28678. })();
  28679. BABYLON.DecimationTriangle = DecimationTriangle;
  28680. var DecimationVertex = (function () {
  28681. function DecimationVertex(position, id) {
  28682. this.position = position;
  28683. this.id = id;
  28684. this.isBorder = true;
  28685. this.q = new QuadraticMatrix();
  28686. this.triangleCount = 0;
  28687. this.triangleStart = 0;
  28688. this.originalOffsets = [];
  28689. }
  28690. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28691. this.position.copyFrom(newPosition);
  28692. };
  28693. return DecimationVertex;
  28694. })();
  28695. BABYLON.DecimationVertex = DecimationVertex;
  28696. var QuadraticMatrix = (function () {
  28697. function QuadraticMatrix(data) {
  28698. this.data = new Array(10);
  28699. for (var i = 0; i < 10; ++i) {
  28700. if (data && data[i]) {
  28701. this.data[i] = data[i];
  28702. }
  28703. else {
  28704. this.data[i] = 0;
  28705. }
  28706. }
  28707. }
  28708. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28709. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28710. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28711. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28712. return det;
  28713. };
  28714. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28715. for (var i = 0; i < 10; ++i) {
  28716. this.data[i] += matrix.data[i];
  28717. }
  28718. };
  28719. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28720. for (var i = 0; i < 10; ++i) {
  28721. this.data[i] += data[i];
  28722. }
  28723. };
  28724. QuadraticMatrix.prototype.add = function (matrix) {
  28725. var m = new QuadraticMatrix();
  28726. for (var i = 0; i < 10; ++i) {
  28727. m.data[i] = this.data[i] + matrix.data[i];
  28728. }
  28729. return m;
  28730. };
  28731. QuadraticMatrix.FromData = function (a, b, c, d) {
  28732. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28733. };
  28734. //returning an array to avoid garbage collection
  28735. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28736. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28737. };
  28738. return QuadraticMatrix;
  28739. })();
  28740. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28741. var Reference = (function () {
  28742. function Reference(vertexId, triangleId) {
  28743. this.vertexId = vertexId;
  28744. this.triangleId = triangleId;
  28745. }
  28746. return Reference;
  28747. })();
  28748. BABYLON.Reference = Reference;
  28749. /**
  28750. * An implementation of the Quadratic Error simplification algorithm.
  28751. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28752. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28753. * @author RaananW
  28754. */
  28755. var QuadraticErrorSimplification = (function () {
  28756. function QuadraticErrorSimplification(_mesh) {
  28757. this._mesh = _mesh;
  28758. this.initialized = false;
  28759. this.syncIterations = 5000;
  28760. this.aggressiveness = 7;
  28761. this.decimationIterations = 100;
  28762. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28763. }
  28764. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28765. var _this = this;
  28766. this.initDecimatedMesh();
  28767. //iterating through the submeshes array, one after the other.
  28768. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28769. _this.initWithMesh(loop.index, function () {
  28770. _this.runDecimation(settings, loop.index, function () {
  28771. loop.executeNext();
  28772. });
  28773. }, settings.optimizeMesh);
  28774. }, function () {
  28775. setTimeout(function () {
  28776. successCallback(_this._reconstructedMesh);
  28777. }, 0);
  28778. });
  28779. };
  28780. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28781. var _this = this;
  28782. var gCount = 0;
  28783. triangle.vertices.forEach(function (vertex) {
  28784. var count = 0;
  28785. var vPos = vertex.position;
  28786. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28787. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28788. ++count;
  28789. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28790. ++count;
  28791. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28792. ++count;
  28793. if (count > 1) {
  28794. ++gCount;
  28795. }
  28796. ;
  28797. });
  28798. if (gCount > 1) {
  28799. console.log(triangle, gCount);
  28800. }
  28801. return gCount > 1;
  28802. };
  28803. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28804. var _this = this;
  28805. var targetCount = ~~(this.triangles.length * settings.quality);
  28806. var deletedTriangles = 0;
  28807. var triangleCount = this.triangles.length;
  28808. var iterationFunction = function (iteration, callback) {
  28809. setTimeout(function () {
  28810. if (iteration % 5 === 0) {
  28811. _this.updateMesh(iteration === 0);
  28812. }
  28813. for (var i = 0; i < _this.triangles.length; ++i) {
  28814. _this.triangles[i].isDirty = false;
  28815. }
  28816. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28817. var trianglesIterator = function (i) {
  28818. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28819. var t = _this.triangles[tIdx];
  28820. if (!t)
  28821. return;
  28822. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28823. return;
  28824. }
  28825. for (var j = 0; j < 3; ++j) {
  28826. if (t.error[j] < threshold) {
  28827. var deleted0 = [];
  28828. var deleted1 = [];
  28829. var v0 = t.vertices[j];
  28830. var v1 = t.vertices[(j + 1) % 3];
  28831. if (v0.isBorder !== v1.isBorder)
  28832. continue;
  28833. var p = BABYLON.Vector3.Zero();
  28834. var n = BABYLON.Vector3.Zero();
  28835. var uv = BABYLON.Vector2.Zero();
  28836. var color = new BABYLON.Color4(0, 0, 0, 1);
  28837. _this.calculateError(v0, v1, p, n, uv, color);
  28838. var delTr = [];
  28839. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28840. continue;
  28841. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28842. continue;
  28843. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28844. continue;
  28845. var uniqueArray = [];
  28846. delTr.forEach(function (deletedT) {
  28847. if (uniqueArray.indexOf(deletedT) === -1) {
  28848. deletedT.deletePending = true;
  28849. uniqueArray.push(deletedT);
  28850. }
  28851. });
  28852. if (uniqueArray.length % 2 !== 0) {
  28853. continue;
  28854. }
  28855. v0.q = v1.q.add(v0.q);
  28856. v0.updatePosition(p);
  28857. var tStart = _this.references.length;
  28858. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28859. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28860. var tCount = _this.references.length - tStart;
  28861. if (tCount <= v0.triangleCount) {
  28862. if (tCount) {
  28863. for (var c = 0; c < tCount; c++) {
  28864. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28865. }
  28866. }
  28867. }
  28868. else {
  28869. v0.triangleStart = tStart;
  28870. }
  28871. v0.triangleCount = tCount;
  28872. break;
  28873. }
  28874. }
  28875. };
  28876. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28877. }, 0);
  28878. };
  28879. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28880. if (triangleCount - deletedTriangles <= targetCount)
  28881. loop.breakLoop();
  28882. else {
  28883. iterationFunction(loop.index, function () {
  28884. loop.executeNext();
  28885. });
  28886. }
  28887. }, function () {
  28888. setTimeout(function () {
  28889. //reconstruct this part of the mesh
  28890. _this.reconstructMesh(submeshIndex);
  28891. successCallback();
  28892. }, 0);
  28893. });
  28894. };
  28895. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28896. var _this = this;
  28897. this.vertices = [];
  28898. this.triangles = [];
  28899. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28900. var indices = this._mesh.getIndices();
  28901. var submesh = this._mesh.subMeshes[submeshIndex];
  28902. var findInVertices = function (positionToSearch) {
  28903. if (optimizeMesh) {
  28904. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28905. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28906. return _this.vertices[ii];
  28907. }
  28908. }
  28909. }
  28910. return null;
  28911. };
  28912. var vertexReferences = [];
  28913. var vertexInit = function (i) {
  28914. var offset = i + submesh.verticesStart;
  28915. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28916. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28917. vertex.originalOffsets.push(offset);
  28918. if (vertex.id === _this.vertices.length) {
  28919. _this.vertices.push(vertex);
  28920. }
  28921. vertexReferences.push(vertex.id);
  28922. };
  28923. //var totalVertices = mesh.getTotalVertices();
  28924. var totalVertices = submesh.verticesCount;
  28925. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28926. var indicesInit = function (i) {
  28927. var offset = (submesh.indexStart / 3) + i;
  28928. var pos = (offset * 3);
  28929. var i0 = indices[pos + 0];
  28930. var i1 = indices[pos + 1];
  28931. var i2 = indices[pos + 2];
  28932. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28933. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28934. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28935. var triangle = new DecimationTriangle([v0, v1, v2]);
  28936. triangle.originalOffset = pos;
  28937. _this.triangles.push(triangle);
  28938. };
  28939. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28940. _this.init(callback);
  28941. });
  28942. });
  28943. };
  28944. QuadraticErrorSimplification.prototype.init = function (callback) {
  28945. var _this = this;
  28946. var triangleInit1 = function (i) {
  28947. var t = _this.triangles[i];
  28948. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28949. for (var j = 0; j < 3; j++) {
  28950. 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))));
  28951. }
  28952. };
  28953. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28954. var triangleInit2 = function (i) {
  28955. var t = _this.triangles[i];
  28956. for (var j = 0; j < 3; ++j) {
  28957. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28958. }
  28959. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28960. };
  28961. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28962. _this.initialized = true;
  28963. callback();
  28964. });
  28965. });
  28966. };
  28967. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28968. var newTriangles = [];
  28969. var i;
  28970. for (i = 0; i < this.vertices.length; ++i) {
  28971. this.vertices[i].triangleCount = 0;
  28972. }
  28973. var t;
  28974. var j;
  28975. for (i = 0; i < this.triangles.length; ++i) {
  28976. if (!this.triangles[i].deleted) {
  28977. t = this.triangles[i];
  28978. for (j = 0; j < 3; ++j) {
  28979. t.vertices[j].triangleCount = 1;
  28980. }
  28981. newTriangles.push(t);
  28982. }
  28983. }
  28984. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  28985. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  28986. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  28987. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  28988. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28989. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28990. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28991. var vertexCount = 0;
  28992. for (i = 0; i < this.vertices.length; ++i) {
  28993. var vertex = this.vertices[i];
  28994. vertex.id = vertexCount;
  28995. if (vertex.triangleCount) {
  28996. vertex.originalOffsets.forEach(function (originalOffset) {
  28997. newPositionData.push(vertex.position.x);
  28998. newPositionData.push(vertex.position.y);
  28999. newPositionData.push(vertex.position.z);
  29000. newNormalData.push(normalData[originalOffset * 3]);
  29001. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29002. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29003. if (uvs && uvs.length) {
  29004. newUVsData.push(uvs[(originalOffset * 2)]);
  29005. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29006. }
  29007. else if (colorsData && colorsData.length) {
  29008. newColorsData.push(colorsData[(originalOffset * 4)]);
  29009. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29010. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29011. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29012. }
  29013. ++vertexCount;
  29014. });
  29015. }
  29016. }
  29017. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29018. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29019. var submeshesArray = this._reconstructedMesh.subMeshes;
  29020. this._reconstructedMesh.subMeshes = [];
  29021. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29022. var originalIndices = this._mesh.getIndices();
  29023. for (i = 0; i < newTriangles.length; ++i) {
  29024. t = newTriangles[i]; //now get the new referencing point for each vertex
  29025. [0, 1, 2].forEach(function (idx) {
  29026. var id = originalIndices[t.originalOffset + idx];
  29027. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29028. if (offset < 0)
  29029. offset = 0;
  29030. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29031. });
  29032. }
  29033. //overwriting the old vertex buffers and indices.
  29034. this._reconstructedMesh.setIndices(newIndicesArray);
  29035. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29036. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29037. if (newUVsData.length > 0)
  29038. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29039. if (newColorsData.length > 0)
  29040. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29041. //create submesh
  29042. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29043. if (submeshIndex > 0) {
  29044. this._reconstructedMesh.subMeshes = [];
  29045. submeshesArray.forEach(function (submesh) {
  29046. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29047. });
  29048. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29049. }
  29050. };
  29051. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29052. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29053. this._reconstructedMesh.material = this._mesh.material;
  29054. this._reconstructedMesh.parent = this._mesh.parent;
  29055. this._reconstructedMesh.isVisible = false;
  29056. };
  29057. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29058. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29059. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29060. if (t.deleted)
  29061. continue;
  29062. var s = this.references[vertex1.triangleStart + i].vertexId;
  29063. var v1 = t.vertices[(s + 1) % 3];
  29064. var v2 = t.vertices[(s + 2) % 3];
  29065. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29066. deletedArray[i] = true;
  29067. delTr.push(t);
  29068. continue;
  29069. }
  29070. var d1 = v1.position.subtract(point);
  29071. d1 = d1.normalize();
  29072. var d2 = v2.position.subtract(point);
  29073. d2 = d2.normalize();
  29074. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29075. return true;
  29076. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29077. deletedArray[i] = false;
  29078. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29079. return true;
  29080. }
  29081. return false;
  29082. };
  29083. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29084. var newDeleted = deletedTriangles;
  29085. for (var i = 0; i < vertex.triangleCount; ++i) {
  29086. var ref = this.references[vertex.triangleStart + i];
  29087. var t = this.triangles[ref.triangleId];
  29088. if (t.deleted)
  29089. continue;
  29090. if (deletedArray[i] && t.deletePending) {
  29091. t.deleted = true;
  29092. newDeleted++;
  29093. continue;
  29094. }
  29095. t.vertices[ref.vertexId] = origVertex;
  29096. t.isDirty = true;
  29097. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29098. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29099. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29100. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29101. this.references.push(ref);
  29102. }
  29103. return newDeleted;
  29104. };
  29105. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29106. for (var i = 0; i < this.vertices.length; ++i) {
  29107. var vCount = [];
  29108. var vId = [];
  29109. var v = this.vertices[i];
  29110. var j;
  29111. for (j = 0; j < v.triangleCount; ++j) {
  29112. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29113. for (var ii = 0; ii < 3; ii++) {
  29114. var ofs = 0;
  29115. var vv = triangle.vertices[ii];
  29116. while (ofs < vCount.length) {
  29117. if (vId[ofs] === vv.id)
  29118. break;
  29119. ++ofs;
  29120. }
  29121. if (ofs === vCount.length) {
  29122. vCount.push(1);
  29123. vId.push(vv.id);
  29124. }
  29125. else {
  29126. vCount[ofs]++;
  29127. }
  29128. }
  29129. }
  29130. for (j = 0; j < vCount.length; ++j) {
  29131. if (vCount[j] === 1) {
  29132. this.vertices[vId[j]].isBorder = true;
  29133. }
  29134. else {
  29135. this.vertices[vId[j]].isBorder = false;
  29136. }
  29137. }
  29138. }
  29139. };
  29140. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29141. if (identifyBorders === void 0) { identifyBorders = false; }
  29142. var i;
  29143. if (!identifyBorders) {
  29144. var newTrianglesVector = [];
  29145. for (i = 0; i < this.triangles.length; ++i) {
  29146. if (!this.triangles[i].deleted) {
  29147. newTrianglesVector.push(this.triangles[i]);
  29148. }
  29149. }
  29150. this.triangles = newTrianglesVector;
  29151. }
  29152. for (i = 0; i < this.vertices.length; ++i) {
  29153. this.vertices[i].triangleCount = 0;
  29154. this.vertices[i].triangleStart = 0;
  29155. }
  29156. var t;
  29157. var j;
  29158. var v;
  29159. for (i = 0; i < this.triangles.length; ++i) {
  29160. t = this.triangles[i];
  29161. for (j = 0; j < 3; ++j) {
  29162. v = t.vertices[j];
  29163. v.triangleCount++;
  29164. }
  29165. }
  29166. var tStart = 0;
  29167. for (i = 0; i < this.vertices.length; ++i) {
  29168. this.vertices[i].triangleStart = tStart;
  29169. tStart += this.vertices[i].triangleCount;
  29170. this.vertices[i].triangleCount = 0;
  29171. }
  29172. var newReferences = new Array(this.triangles.length * 3);
  29173. for (i = 0; i < this.triangles.length; ++i) {
  29174. t = this.triangles[i];
  29175. for (j = 0; j < 3; ++j) {
  29176. v = t.vertices[j];
  29177. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29178. v.triangleCount++;
  29179. }
  29180. }
  29181. this.references = newReferences;
  29182. if (identifyBorders) {
  29183. this.identifyBorder();
  29184. }
  29185. };
  29186. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29187. var x = point.x;
  29188. var y = point.y;
  29189. var z = point.z;
  29190. 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
  29191. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29192. };
  29193. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29194. var q = vertex1.q.add(vertex2.q);
  29195. var border = vertex1.isBorder && vertex2.isBorder;
  29196. var error = 0;
  29197. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29198. if (qDet !== 0 && !border) {
  29199. if (!pointResult) {
  29200. pointResult = BABYLON.Vector3.Zero();
  29201. }
  29202. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29203. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29204. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29205. error = this.vertexError(q, pointResult);
  29206. }
  29207. else {
  29208. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29209. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29210. var error1 = this.vertexError(q, vertex1.position);
  29211. var error2 = this.vertexError(q, vertex2.position);
  29212. var error3 = this.vertexError(q, p3);
  29213. error = Math.min(error1, error2, error3);
  29214. if (error === error1) {
  29215. if (pointResult) {
  29216. pointResult.copyFrom(vertex1.position);
  29217. }
  29218. }
  29219. else if (error === error2) {
  29220. if (pointResult) {
  29221. pointResult.copyFrom(vertex2.position);
  29222. }
  29223. }
  29224. else {
  29225. if (pointResult) {
  29226. pointResult.copyFrom(p3);
  29227. }
  29228. }
  29229. }
  29230. return error;
  29231. };
  29232. return QuadraticErrorSimplification;
  29233. })();
  29234. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29235. })(BABYLON || (BABYLON = {}));
  29236. var BABYLON;
  29237. (function (BABYLON) {
  29238. var serializeLight = function (light) {
  29239. var serializationObject = {};
  29240. serializationObject.name = light.name;
  29241. serializationObject.id = light.id;
  29242. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29243. if (light instanceof BABYLON.PointLight) {
  29244. serializationObject.type = 0;
  29245. serializationObject.position = (light).position.asArray();
  29246. }
  29247. else if (light instanceof BABYLON.DirectionalLight) {
  29248. serializationObject.type = 1;
  29249. var directionalLight = light;
  29250. serializationObject.position = directionalLight.position.asArray();
  29251. serializationObject.direction = directionalLight.direction.asArray();
  29252. }
  29253. else if (light instanceof BABYLON.SpotLight) {
  29254. serializationObject.type = 2;
  29255. var spotLight = light;
  29256. serializationObject.position = spotLight.position.asArray();
  29257. serializationObject.direction = spotLight.position.asArray();
  29258. serializationObject.angle = spotLight.angle;
  29259. serializationObject.exponent = spotLight.exponent;
  29260. }
  29261. else if (light instanceof BABYLON.HemisphericLight) {
  29262. serializationObject.type = 3;
  29263. var hemisphericLight = light;
  29264. serializationObject.direction = hemisphericLight.direction.asArray();
  29265. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29266. }
  29267. if (light.intensity) {
  29268. serializationObject.intensity = light.intensity;
  29269. }
  29270. serializationObject.range = light.range;
  29271. serializationObject.diffuse = light.diffuse.asArray();
  29272. serializationObject.specular = light.specular.asArray();
  29273. return serializationObject;
  29274. };
  29275. var serializeFresnelParameter = function (fresnelParameter) {
  29276. var serializationObject = {};
  29277. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29278. serializationObject.leftColor = fresnelParameter.leftColor;
  29279. serializationObject.rightColor = fresnelParameter.rightColor;
  29280. serializationObject.bias = fresnelParameter.bias;
  29281. serializationObject.power = fresnelParameter.power;
  29282. return serializationObject;
  29283. };
  29284. var serializeAnimation;
  29285. var appendAnimations = function (source, destination) {
  29286. if (source.animations) {
  29287. destination.animations = [];
  29288. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29289. var animation = source.animations[animationIndex];
  29290. destination.animations.push(serializeAnimation(animation));
  29291. }
  29292. }
  29293. };
  29294. var serializeCamera = function (camera) {
  29295. var serializationObject = {};
  29296. serializationObject.name = camera.name;
  29297. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29298. serializationObject.id = camera.id;
  29299. serializationObject.position = camera.position.asArray();
  29300. // Parent
  29301. if (camera.parent) {
  29302. serializationObject.parentId = camera.parent.id;
  29303. }
  29304. serializationObject.fov = camera.fov;
  29305. serializationObject.minZ = camera.minZ;
  29306. serializationObject.maxZ = camera.maxZ;
  29307. serializationObject.inertia = camera.inertia;
  29308. //setting the type
  29309. if (camera instanceof BABYLON.FreeCamera) {
  29310. serializationObject.type = "FreeCamera";
  29311. }
  29312. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29313. serializationObject.type = "ArcRotateCamera";
  29314. }
  29315. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29316. serializationObject.type = "AnaglyphArcRotateCamera";
  29317. }
  29318. else if (camera instanceof BABYLON.GamepadCamera) {
  29319. serializationObject.type = "GamepadCamera";
  29320. }
  29321. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29322. serializationObject.type = "AnaglyphFreeCamera";
  29323. }
  29324. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29325. serializationObject.type = "DeviceOrientationCamera";
  29326. }
  29327. else if (camera instanceof BABYLON.FollowCamera) {
  29328. serializationObject.type = "FollowCamera";
  29329. }
  29330. else if (camera instanceof BABYLON.TouchCamera) {
  29331. serializationObject.type = "TouchCamera";
  29332. }
  29333. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29334. serializationObject.type = "VirtualJoysticksCamera";
  29335. }
  29336. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29337. serializationObject.type = "WebVRFreeCamera";
  29338. }
  29339. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29340. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29341. }
  29342. //special properties of specific cameras
  29343. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29344. var arcCamera = camera;
  29345. serializationObject.alpha = arcCamera.alpha;
  29346. serializationObject.beta = arcCamera.beta;
  29347. serializationObject.radius = arcCamera.radius;
  29348. if (arcCamera.target && arcCamera.target.id) {
  29349. serializationObject.lockedTargetId = arcCamera.target.id;
  29350. }
  29351. }
  29352. else if (camera instanceof BABYLON.FollowCamera) {
  29353. var followCam = camera;
  29354. serializationObject.radius = followCam.radius;
  29355. serializationObject.heightOffset = followCam.heightOffset;
  29356. serializationObject.rotationOffset = followCam.rotationOffset;
  29357. }
  29358. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29359. //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.
  29360. if (camera['_interaxialDistance'] !== undefined) {
  29361. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29362. }
  29363. }
  29364. //general properties that not all cameras have. The [] is due to typescript's type safety
  29365. if (camera['speed'] !== undefined) {
  29366. serializationObject.speed = camera['speed'];
  29367. }
  29368. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29369. serializationObject.target = camera['target'].asArray();
  29370. }
  29371. // Target
  29372. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29373. serializationObject.rotation = camera['rotation'].asArray();
  29374. }
  29375. // Locked target
  29376. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29377. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29378. }
  29379. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29380. serializationObject.applyGravity = camera['applyGravity'] || false;
  29381. if (camera['ellipsoid']) {
  29382. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29383. }
  29384. // Animations
  29385. appendAnimations(camera, serializationObject);
  29386. // Layer mask
  29387. serializationObject.layerMask = camera.layerMask;
  29388. return serializationObject;
  29389. };
  29390. serializeAnimation = function (animation) {
  29391. var serializationObject = {};
  29392. serializationObject.name = animation.name;
  29393. serializationObject.property = animation.targetProperty;
  29394. serializationObject.framePerSecond = animation.framePerSecond;
  29395. serializationObject.dataType = animation.dataType;
  29396. serializationObject.loopBehavior = animation.loopMode;
  29397. var dataType = animation.dataType;
  29398. serializationObject.keys = [];
  29399. var keys = animation.getKeys();
  29400. for (var index = 0; index < keys.length; index++) {
  29401. var animationKey = keys[index];
  29402. var key = {};
  29403. key.frame = animationKey.frame;
  29404. switch (dataType) {
  29405. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29406. key.values = [animationKey.value];
  29407. break;
  29408. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29409. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29410. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29411. key.values = animationKey.value.asArray();
  29412. break;
  29413. }
  29414. serializationObject.keys.push(key);
  29415. }
  29416. return serializationObject;
  29417. };
  29418. var serializeMultiMaterial = function (material) {
  29419. var serializationObject = {};
  29420. serializationObject.name = material.name;
  29421. serializationObject.id = material.id;
  29422. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29423. serializationObject.materials = [];
  29424. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29425. var subMat = material.subMaterials[matIndex];
  29426. if (subMat) {
  29427. serializationObject.materials.push(subMat.id);
  29428. }
  29429. else {
  29430. serializationObject.materials.push(null);
  29431. }
  29432. }
  29433. return serializationObject;
  29434. };
  29435. var serializeTexture;
  29436. var serializeMaterial = function (material) {
  29437. var serializationObject = {};
  29438. serializationObject.name = material.name;
  29439. serializationObject.ambient = material.ambientColor.asArray();
  29440. serializationObject.diffuse = material.diffuseColor.asArray();
  29441. serializationObject.specular = material.specularColor.asArray();
  29442. serializationObject.specularPower = material.specularPower;
  29443. serializationObject.emissive = material.emissiveColor.asArray();
  29444. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29445. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29446. serializationObject.alpha = material.alpha;
  29447. serializationObject.id = material.id;
  29448. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29449. serializationObject.backFaceCulling = material.backFaceCulling;
  29450. if (material.diffuseTexture) {
  29451. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29452. }
  29453. if (material.diffuseFresnelParameters) {
  29454. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29455. }
  29456. if (material.ambientTexture) {
  29457. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29458. }
  29459. if (material.opacityTexture) {
  29460. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29461. }
  29462. if (material.opacityFresnelParameters) {
  29463. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29464. }
  29465. if (material.reflectionTexture) {
  29466. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29467. }
  29468. if (material.reflectionFresnelParameters) {
  29469. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29470. }
  29471. if (material.emissiveTexture) {
  29472. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29473. }
  29474. if (material.lightmapTexture) {
  29475. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29476. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29477. }
  29478. if (material.emissiveFresnelParameters) {
  29479. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29480. }
  29481. if (material.specularTexture) {
  29482. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29483. }
  29484. if (material.bumpTexture) {
  29485. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29486. }
  29487. return serializationObject;
  29488. };
  29489. serializeTexture = function (texture) {
  29490. var serializationObject = {};
  29491. if (!texture.name) {
  29492. return null;
  29493. }
  29494. if (texture instanceof BABYLON.CubeTexture) {
  29495. serializationObject.name = texture.name;
  29496. serializationObject.hasAlpha = texture.hasAlpha;
  29497. serializationObject.isCube = true;
  29498. serializationObject.level = texture.level;
  29499. serializationObject.coordinatesMode = texture.coordinatesMode;
  29500. return serializationObject;
  29501. }
  29502. var index;
  29503. if (texture instanceof BABYLON.MirrorTexture) {
  29504. var mirrorTexture = texture;
  29505. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29506. serializationObject.renderList = [];
  29507. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29508. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29509. }
  29510. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29511. }
  29512. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29513. var renderTargetTexture = texture;
  29514. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29515. serializationObject.renderList = [];
  29516. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29517. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29518. }
  29519. }
  29520. var regularTexture = texture;
  29521. serializationObject.name = texture.name;
  29522. serializationObject.hasAlpha = texture.hasAlpha;
  29523. serializationObject.level = texture.level;
  29524. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29525. serializationObject.coordinatesMode = texture.coordinatesMode;
  29526. serializationObject.uOffset = regularTexture.uOffset;
  29527. serializationObject.vOffset = regularTexture.vOffset;
  29528. serializationObject.uScale = regularTexture.uScale;
  29529. serializationObject.vScale = regularTexture.vScale;
  29530. serializationObject.uAng = regularTexture.uAng;
  29531. serializationObject.vAng = regularTexture.vAng;
  29532. serializationObject.wAng = regularTexture.wAng;
  29533. serializationObject.wrapU = texture.wrapU;
  29534. serializationObject.wrapV = texture.wrapV;
  29535. // Animations
  29536. appendAnimations(texture, serializationObject);
  29537. return serializationObject;
  29538. };
  29539. var serializeSkeleton = function (skeleton) {
  29540. var serializationObject = {};
  29541. serializationObject.name = skeleton.name;
  29542. serializationObject.id = skeleton.id;
  29543. serializationObject.bones = [];
  29544. for (var index = 0; index < skeleton.bones.length; index++) {
  29545. var bone = skeleton.bones[index];
  29546. var serializedBone = {
  29547. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29548. name: bone.name,
  29549. matrix: bone.getLocalMatrix().toArray()
  29550. };
  29551. serializationObject.bones.push(serializedBone);
  29552. if (bone.animations && bone.animations.length > 0) {
  29553. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29554. }
  29555. }
  29556. return serializationObject;
  29557. };
  29558. var serializeParticleSystem = function (particleSystem) {
  29559. var serializationObject = {};
  29560. serializationObject.emitterId = particleSystem.emitter.id;
  29561. serializationObject.capacity = particleSystem.getCapacity();
  29562. if (particleSystem.particleTexture) {
  29563. serializationObject.textureName = particleSystem.particleTexture.name;
  29564. }
  29565. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29566. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29567. serializationObject.minSize = particleSystem.minSize;
  29568. serializationObject.maxSize = particleSystem.maxSize;
  29569. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29570. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29571. serializationObject.emitRate = particleSystem.emitRate;
  29572. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29573. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29574. serializationObject.gravity = particleSystem.gravity.asArray();
  29575. serializationObject.direction1 = particleSystem.direction1.asArray();
  29576. serializationObject.direction2 = particleSystem.direction2.asArray();
  29577. serializationObject.color1 = particleSystem.color1.asArray();
  29578. serializationObject.color2 = particleSystem.color2.asArray();
  29579. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29580. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29581. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29582. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29583. serializationObject.blendMode = particleSystem.blendMode;
  29584. return serializationObject;
  29585. };
  29586. var serializeLensFlareSystem = function (lensFlareSystem) {
  29587. var serializationObject = {};
  29588. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29589. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29590. serializationObject.flares = [];
  29591. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29592. var flare = lensFlareSystem.lensFlares[index];
  29593. serializationObject.flares.push({
  29594. size: flare.size,
  29595. position: flare.position,
  29596. color: flare.color.asArray(),
  29597. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29598. });
  29599. }
  29600. return serializationObject;
  29601. };
  29602. var serializeShadowGenerator = function (light) {
  29603. var serializationObject = {};
  29604. var shadowGenerator = light.getShadowGenerator();
  29605. serializationObject.lightId = light.id;
  29606. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29607. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29608. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29609. serializationObject.renderList = [];
  29610. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29611. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29612. serializationObject.renderList.push(mesh.id);
  29613. }
  29614. return serializationObject;
  29615. };
  29616. var serializedGeometries = [];
  29617. var serializeVertexData;
  29618. var serializeTorusKnot;
  29619. var serializePlane;
  29620. var serializeGround;
  29621. var serializeTorus;
  29622. var serializeCylinder;
  29623. var serializeSphere;
  29624. var serializeBox;
  29625. var serializeGeometry = function (geometry, serializationGeometries) {
  29626. if (serializedGeometries[geometry.id]) {
  29627. return;
  29628. }
  29629. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29630. serializationGeometries.boxes.push(serializeBox(geometry));
  29631. }
  29632. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29633. serializationGeometries.spheres.push(serializeSphere(geometry));
  29634. }
  29635. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29636. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29637. }
  29638. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29639. serializationGeometries.toruses.push(serializeTorus(geometry));
  29640. }
  29641. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29642. serializationGeometries.grounds.push(serializeGround(geometry));
  29643. }
  29644. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29645. serializationGeometries.planes.push(serializePlane(geometry));
  29646. }
  29647. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29648. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29649. }
  29650. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29651. throw new Error("Unknown primitive type");
  29652. }
  29653. else {
  29654. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29655. }
  29656. serializedGeometries[geometry.id] = true;
  29657. };
  29658. var serializeGeometryBase = function (geometry) {
  29659. var serializationObject = {};
  29660. serializationObject.id = geometry.id;
  29661. if (BABYLON.Tags.HasTags(geometry)) {
  29662. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29663. }
  29664. return serializationObject;
  29665. };
  29666. serializeVertexData = function (vertexData) {
  29667. var serializationObject = serializeGeometryBase(vertexData);
  29668. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29669. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29670. }
  29671. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29672. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29673. }
  29674. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29675. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29676. }
  29677. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29678. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29679. }
  29680. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29681. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29682. }
  29683. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29684. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29685. }
  29686. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29687. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29688. }
  29689. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29690. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29691. }
  29692. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29693. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29694. }
  29695. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29696. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29697. serializationObject.matricesIndices._isExpanded = true;
  29698. }
  29699. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29700. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29701. }
  29702. serializationObject.indices = vertexData.getIndices();
  29703. return serializationObject;
  29704. };
  29705. var serializePrimitive = function (primitive) {
  29706. var serializationObject = serializeGeometryBase(primitive);
  29707. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29708. return serializationObject;
  29709. };
  29710. serializeBox = function (box) {
  29711. var serializationObject = serializePrimitive(box);
  29712. serializationObject.size = box.size;
  29713. return serializationObject;
  29714. };
  29715. serializeSphere = function (sphere) {
  29716. var serializationObject = serializePrimitive(sphere);
  29717. serializationObject.segments = sphere.segments;
  29718. serializationObject.diameter = sphere.diameter;
  29719. return serializationObject;
  29720. };
  29721. serializeCylinder = function (cylinder) {
  29722. var serializationObject = serializePrimitive(cylinder);
  29723. serializationObject.height = cylinder.height;
  29724. serializationObject.diameterTop = cylinder.diameterTop;
  29725. serializationObject.diameterBottom = cylinder.diameterBottom;
  29726. serializationObject.tessellation = cylinder.tessellation;
  29727. return serializationObject;
  29728. };
  29729. serializeTorus = function (torus) {
  29730. var serializationObject = serializePrimitive(torus);
  29731. serializationObject.diameter = torus.diameter;
  29732. serializationObject.thickness = torus.thickness;
  29733. serializationObject.tessellation = torus.tessellation;
  29734. return serializationObject;
  29735. };
  29736. serializeGround = function (ground) {
  29737. var serializationObject = serializePrimitive(ground);
  29738. serializationObject.width = ground.width;
  29739. serializationObject.height = ground.height;
  29740. serializationObject.subdivisions = ground.subdivisions;
  29741. return serializationObject;
  29742. };
  29743. serializePlane = function (plane) {
  29744. var serializationObject = serializePrimitive(plane);
  29745. serializationObject.size = plane.size;
  29746. return serializationObject;
  29747. };
  29748. serializeTorusKnot = function (torusKnot) {
  29749. var serializationObject = serializePrimitive(torusKnot);
  29750. serializationObject.radius = torusKnot.radius;
  29751. serializationObject.tube = torusKnot.tube;
  29752. serializationObject.radialSegments = torusKnot.radialSegments;
  29753. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29754. serializationObject.p = torusKnot.p;
  29755. serializationObject.q = torusKnot.q;
  29756. return serializationObject;
  29757. };
  29758. var serializeMesh = function (mesh, serializationScene) {
  29759. var serializationObject = {};
  29760. serializationObject.name = mesh.name;
  29761. serializationObject.id = mesh.id;
  29762. if (BABYLON.Tags.HasTags(mesh)) {
  29763. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29764. }
  29765. serializationObject.position = mesh.position.asArray();
  29766. if (mesh.rotationQuaternion) {
  29767. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29768. }
  29769. else if (mesh.rotation) {
  29770. serializationObject.rotation = mesh.rotation.asArray();
  29771. }
  29772. serializationObject.scaling = mesh.scaling.asArray();
  29773. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29774. serializationObject.isEnabled = mesh.isEnabled();
  29775. serializationObject.isVisible = mesh.isVisible;
  29776. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29777. serializationObject.pickable = mesh.isPickable;
  29778. serializationObject.receiveShadows = mesh.receiveShadows;
  29779. serializationObject.billboardMode = mesh.billboardMode;
  29780. serializationObject.visibility = mesh.visibility;
  29781. serializationObject.checkCollisions = mesh.checkCollisions;
  29782. // Parent
  29783. if (mesh.parent) {
  29784. serializationObject.parentId = mesh.parent.id;
  29785. }
  29786. // Geometry
  29787. var geometry = mesh._geometry;
  29788. if (geometry) {
  29789. var geometryId = geometry.id;
  29790. serializationObject.geometryId = geometryId;
  29791. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29792. // 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
  29793. serializeGeometry(geometry, serializationScene.geometries);
  29794. }
  29795. // SubMeshes
  29796. serializationObject.subMeshes = [];
  29797. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29798. var subMesh = mesh.subMeshes[subIndex];
  29799. serializationObject.subMeshes.push({
  29800. materialIndex: subMesh.materialIndex,
  29801. verticesStart: subMesh.verticesStart,
  29802. verticesCount: subMesh.verticesCount,
  29803. indexStart: subMesh.indexStart,
  29804. indexCount: subMesh.indexCount
  29805. });
  29806. }
  29807. }
  29808. // Material
  29809. if (mesh.material) {
  29810. serializationObject.materialId = mesh.material.id;
  29811. }
  29812. else {
  29813. mesh.material = null;
  29814. }
  29815. // Skeleton
  29816. if (mesh.skeleton) {
  29817. serializationObject.skeletonId = mesh.skeleton.id;
  29818. }
  29819. // Physics
  29820. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29821. serializationObject.physicsMass = mesh.getPhysicsMass();
  29822. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29823. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29824. switch (mesh.getPhysicsImpostor()) {
  29825. case BABYLON.PhysicsEngine.BoxImpostor:
  29826. serializationObject.physicsImpostor = 1;
  29827. break;
  29828. case BABYLON.PhysicsEngine.SphereImpostor:
  29829. serializationObject.physicsImpostor = 2;
  29830. break;
  29831. }
  29832. }
  29833. // Instances
  29834. serializationObject.instances = [];
  29835. for (var index = 0; index < mesh.instances.length; index++) {
  29836. var instance = mesh.instances[index];
  29837. var serializationInstance = {
  29838. name: instance.name,
  29839. position: instance.position.asArray(),
  29840. rotation: instance.rotation.asArray(),
  29841. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29842. scaling: instance.scaling.asArray()
  29843. };
  29844. serializationObject.instances.push(serializationInstance);
  29845. // Animations
  29846. appendAnimations(instance, serializationInstance);
  29847. }
  29848. // Animations
  29849. appendAnimations(mesh, serializationObject);
  29850. // Layer mask
  29851. serializationObject.layerMask = mesh.layerMask;
  29852. return serializationObject;
  29853. };
  29854. var finalizeSingleMesh = function (mesh, serializationObject) {
  29855. //only works if the mesh is already loaded
  29856. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29857. //serialize material
  29858. if (mesh.material) {
  29859. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29860. serializationObject.materials = serializationObject.materials || [];
  29861. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29862. serializationObject.materials.push(serializeMaterial(mesh.material));
  29863. }
  29864. }
  29865. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29866. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29867. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29868. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29869. }
  29870. }
  29871. }
  29872. //serialize geometry
  29873. var geometry = mesh._geometry;
  29874. if (geometry) {
  29875. if (!serializationObject.geometries) {
  29876. serializationObject.geometries = {};
  29877. serializationObject.geometries.boxes = [];
  29878. serializationObject.geometries.spheres = [];
  29879. serializationObject.geometries.cylinders = [];
  29880. serializationObject.geometries.toruses = [];
  29881. serializationObject.geometries.grounds = [];
  29882. serializationObject.geometries.planes = [];
  29883. serializationObject.geometries.torusKnots = [];
  29884. serializationObject.geometries.vertexData = [];
  29885. }
  29886. serializeGeometry(geometry, serializationObject.geometries);
  29887. }
  29888. // Skeletons
  29889. if (mesh.skeleton) {
  29890. serializationObject.skeletons = serializationObject.skeletons || [];
  29891. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29892. }
  29893. //serialize the actual mesh
  29894. serializationObject.meshes = serializationObject.meshes || [];
  29895. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29896. }
  29897. };
  29898. var SceneSerializer = (function () {
  29899. function SceneSerializer() {
  29900. }
  29901. SceneSerializer.Serialize = function (scene) {
  29902. var serializationObject = {};
  29903. // Scene
  29904. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29905. serializationObject.autoClear = scene.autoClear;
  29906. serializationObject.clearColor = scene.clearColor.asArray();
  29907. serializationObject.ambientColor = scene.ambientColor.asArray();
  29908. serializationObject.gravity = scene.gravity.asArray();
  29909. // Fog
  29910. if (scene.fogMode && scene.fogMode !== 0) {
  29911. serializationObject.fogMode = scene.fogMode;
  29912. serializationObject.fogColor = scene.fogColor.asArray();
  29913. serializationObject.fogStart = scene.fogStart;
  29914. serializationObject.fogEnd = scene.fogEnd;
  29915. serializationObject.fogDensity = scene.fogDensity;
  29916. }
  29917. // Lights
  29918. serializationObject.lights = [];
  29919. var index;
  29920. var light;
  29921. for (index = 0; index < scene.lights.length; index++) {
  29922. light = scene.lights[index];
  29923. serializationObject.lights.push(serializeLight(light));
  29924. }
  29925. // Cameras
  29926. serializationObject.cameras = [];
  29927. for (index = 0; index < scene.cameras.length; index++) {
  29928. var camera = scene.cameras[index];
  29929. serializationObject.cameras.push(serializeCamera(camera));
  29930. }
  29931. if (scene.activeCamera) {
  29932. serializationObject.activeCameraID = scene.activeCamera.id;
  29933. }
  29934. // Materials
  29935. serializationObject.materials = [];
  29936. serializationObject.multiMaterials = [];
  29937. var material;
  29938. for (index = 0; index < scene.materials.length; index++) {
  29939. material = scene.materials[index];
  29940. serializationObject.materials.push(serializeMaterial(material));
  29941. }
  29942. // MultiMaterials
  29943. serializationObject.multiMaterials = [];
  29944. for (index = 0; index < scene.multiMaterials.length; index++) {
  29945. var multiMaterial = scene.multiMaterials[index];
  29946. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  29947. }
  29948. for (index = 0; index < scene.materials.length; index++) {
  29949. material = scene.materials[index];
  29950. if (material instanceof BABYLON.StandardMaterial) {
  29951. serializationObject.materials.push(serializeMaterial(material));
  29952. }
  29953. else if (material instanceof BABYLON.MultiMaterial) {
  29954. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  29955. }
  29956. }
  29957. // Skeletons
  29958. serializationObject.skeletons = [];
  29959. for (index = 0; index < scene.skeletons.length; index++) {
  29960. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  29961. }
  29962. // Geometries
  29963. serializationObject.geometries = {};
  29964. serializationObject.geometries.boxes = [];
  29965. serializationObject.geometries.spheres = [];
  29966. serializationObject.geometries.cylinders = [];
  29967. serializationObject.geometries.toruses = [];
  29968. serializationObject.geometries.grounds = [];
  29969. serializationObject.geometries.planes = [];
  29970. serializationObject.geometries.torusKnots = [];
  29971. serializationObject.geometries.vertexData = [];
  29972. serializedGeometries = [];
  29973. var geometries = scene.getGeometries();
  29974. for (index = 0; index < geometries.length; index++) {
  29975. var geometry = geometries[index];
  29976. if (geometry.isReady()) {
  29977. serializeGeometry(geometry, serializationObject.geometries);
  29978. }
  29979. }
  29980. // Meshes
  29981. serializationObject.meshes = [];
  29982. for (index = 0; index < scene.meshes.length; index++) {
  29983. var abstractMesh = scene.meshes[index];
  29984. if (abstractMesh instanceof BABYLON.Mesh) {
  29985. var mesh = abstractMesh;
  29986. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29987. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29988. }
  29989. }
  29990. }
  29991. // Particles Systems
  29992. serializationObject.particleSystems = [];
  29993. for (index = 0; index < scene.particleSystems.length; index++) {
  29994. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  29995. }
  29996. // Lens flares
  29997. serializationObject.lensFlareSystems = [];
  29998. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  29999. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30000. }
  30001. // Shadows
  30002. serializationObject.shadowGenerators = [];
  30003. for (index = 0; index < scene.lights.length; index++) {
  30004. light = scene.lights[index];
  30005. if (light.getShadowGenerator()) {
  30006. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30007. }
  30008. }
  30009. return serializationObject;
  30010. };
  30011. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30012. if (withParents === void 0) { withParents = false; }
  30013. if (withChildren === void 0) { withChildren = false; }
  30014. var serializationObject = {};
  30015. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30016. if (withParents || withChildren) {
  30017. //deliberate for loop! not for each, appended should be processed as well.
  30018. for (var i = 0; i < toSerialize.length; ++i) {
  30019. if (withChildren) {
  30020. toSerialize[i].getDescendants().forEach(function (node) {
  30021. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30022. toSerialize.push(node);
  30023. }
  30024. });
  30025. }
  30026. //make sure the array doesn't contain the object already
  30027. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30028. toSerialize.push(toSerialize[i].parent);
  30029. }
  30030. }
  30031. }
  30032. toSerialize.forEach(function (mesh) {
  30033. finalizeSingleMesh(mesh, serializationObject);
  30034. });
  30035. return serializationObject;
  30036. };
  30037. return SceneSerializer;
  30038. })();
  30039. BABYLON.SceneSerializer = SceneSerializer;
  30040. })(BABYLON || (BABYLON = {}));
  30041. var BABYLON;
  30042. (function (BABYLON) {
  30043. // Unique ID when we import meshes from Babylon to CSG
  30044. var currentCSGMeshId = 0;
  30045. // # class Vertex
  30046. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30047. // one to provide additional features like texture coordinates and vertex
  30048. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30049. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30050. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30051. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30052. // is not used anywhere else.
  30053. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30054. var Vertex = (function () {
  30055. function Vertex(pos, normal, uv) {
  30056. this.pos = pos;
  30057. this.normal = normal;
  30058. this.uv = uv;
  30059. }
  30060. Vertex.prototype.clone = function () {
  30061. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30062. };
  30063. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30064. // orientation of a polygon is flipped.
  30065. Vertex.prototype.flip = function () {
  30066. this.normal = this.normal.scale(-1);
  30067. };
  30068. // Create a new vertex between this vertex and `other` by linearly
  30069. // interpolating all properties using a parameter of `t`. Subclasses should
  30070. // override this to interpolate additional properties.
  30071. Vertex.prototype.interpolate = function (other, t) {
  30072. 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));
  30073. };
  30074. return Vertex;
  30075. })();
  30076. // # class Plane
  30077. // Represents a plane in 3D space.
  30078. var Plane = (function () {
  30079. function Plane(normal, w) {
  30080. this.normal = normal;
  30081. this.w = w;
  30082. }
  30083. Plane.FromPoints = function (a, b, c) {
  30084. var v0 = c.subtract(a);
  30085. var v1 = b.subtract(a);
  30086. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30087. return null;
  30088. }
  30089. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30090. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30091. };
  30092. Plane.prototype.clone = function () {
  30093. return new Plane(this.normal.clone(), this.w);
  30094. };
  30095. Plane.prototype.flip = function () {
  30096. this.normal.scaleInPlace(-1);
  30097. this.w = -this.w;
  30098. };
  30099. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30100. // fragments in the appropriate lists. Coplanar polygons go into either
  30101. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30102. // respect to this plane. Polygons in front or in back of this plane go into
  30103. // either `front` or `back`.
  30104. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30105. var COPLANAR = 0;
  30106. var FRONT = 1;
  30107. var BACK = 2;
  30108. var SPANNING = 3;
  30109. // Classify each point as well as the entire polygon into one of the above
  30110. // four classes.
  30111. var polygonType = 0;
  30112. var types = [];
  30113. var i;
  30114. var t;
  30115. for (i = 0; i < polygon.vertices.length; i++) {
  30116. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30117. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30118. polygonType |= type;
  30119. types.push(type);
  30120. }
  30121. // Put the polygon in the correct list, splitting it when necessary.
  30122. switch (polygonType) {
  30123. case COPLANAR:
  30124. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30125. break;
  30126. case FRONT:
  30127. front.push(polygon);
  30128. break;
  30129. case BACK:
  30130. back.push(polygon);
  30131. break;
  30132. case SPANNING:
  30133. var f = [], b = [];
  30134. for (i = 0; i < polygon.vertices.length; i++) {
  30135. var j = (i + 1) % polygon.vertices.length;
  30136. var ti = types[i], tj = types[j];
  30137. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30138. if (ti !== BACK)
  30139. f.push(vi);
  30140. if (ti !== FRONT)
  30141. b.push(ti !== BACK ? vi.clone() : vi);
  30142. if ((ti | tj) === SPANNING) {
  30143. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30144. var v = vi.interpolate(vj, t);
  30145. f.push(v);
  30146. b.push(v.clone());
  30147. }
  30148. }
  30149. var poly;
  30150. if (f.length >= 3) {
  30151. poly = new Polygon(f, polygon.shared);
  30152. if (poly.plane)
  30153. front.push(poly);
  30154. }
  30155. if (b.length >= 3) {
  30156. poly = new Polygon(b, polygon.shared);
  30157. if (poly.plane)
  30158. back.push(poly);
  30159. }
  30160. break;
  30161. }
  30162. };
  30163. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30164. // point is on the plane.
  30165. Plane.EPSILON = 1e-5;
  30166. return Plane;
  30167. })();
  30168. // # class Polygon
  30169. // Represents a convex polygon. The vertices used to initialize a polygon must
  30170. // be coplanar and form a convex loop.
  30171. //
  30172. // Each convex polygon has a `shared` property, which is shared between all
  30173. // polygons that are clones of each other or were split from the same polygon.
  30174. // This can be used to define per-polygon properties (such as surface color).
  30175. var Polygon = (function () {
  30176. function Polygon(vertices, shared) {
  30177. this.vertices = vertices;
  30178. this.shared = shared;
  30179. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30180. }
  30181. Polygon.prototype.clone = function () {
  30182. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30183. return new Polygon(vertices, this.shared);
  30184. };
  30185. Polygon.prototype.flip = function () {
  30186. this.vertices.reverse().map(function (v) { v.flip(); });
  30187. this.plane.flip();
  30188. };
  30189. return Polygon;
  30190. })();
  30191. // # class Node
  30192. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30193. // by picking a polygon to split along. That polygon (and all other coplanar
  30194. // polygons) are added directly to that node and the other polygons are added to
  30195. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30196. // no distinction between internal and leaf nodes.
  30197. var Node = (function () {
  30198. function Node(polygons) {
  30199. this.plane = null;
  30200. this.front = null;
  30201. this.back = null;
  30202. this.polygons = [];
  30203. if (polygons) {
  30204. this.build(polygons);
  30205. }
  30206. }
  30207. Node.prototype.clone = function () {
  30208. var node = new Node();
  30209. node.plane = this.plane && this.plane.clone();
  30210. node.front = this.front && this.front.clone();
  30211. node.back = this.back && this.back.clone();
  30212. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30213. return node;
  30214. };
  30215. // Convert solid space to empty space and empty space to solid space.
  30216. Node.prototype.invert = function () {
  30217. for (var i = 0; i < this.polygons.length; i++) {
  30218. this.polygons[i].flip();
  30219. }
  30220. if (this.plane) {
  30221. this.plane.flip();
  30222. }
  30223. if (this.front) {
  30224. this.front.invert();
  30225. }
  30226. if (this.back) {
  30227. this.back.invert();
  30228. }
  30229. var temp = this.front;
  30230. this.front = this.back;
  30231. this.back = temp;
  30232. };
  30233. // Recursively remove all polygons in `polygons` that are inside this BSP
  30234. // tree.
  30235. Node.prototype.clipPolygons = function (polygons) {
  30236. if (!this.plane)
  30237. return polygons.slice();
  30238. var front = [], back = [];
  30239. for (var i = 0; i < polygons.length; i++) {
  30240. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30241. }
  30242. if (this.front) {
  30243. front = this.front.clipPolygons(front);
  30244. }
  30245. if (this.back) {
  30246. back = this.back.clipPolygons(back);
  30247. }
  30248. else {
  30249. back = [];
  30250. }
  30251. return front.concat(back);
  30252. };
  30253. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30254. // `bsp`.
  30255. Node.prototype.clipTo = function (bsp) {
  30256. this.polygons = bsp.clipPolygons(this.polygons);
  30257. if (this.front)
  30258. this.front.clipTo(bsp);
  30259. if (this.back)
  30260. this.back.clipTo(bsp);
  30261. };
  30262. // Return a list of all polygons in this BSP tree.
  30263. Node.prototype.allPolygons = function () {
  30264. var polygons = this.polygons.slice();
  30265. if (this.front)
  30266. polygons = polygons.concat(this.front.allPolygons());
  30267. if (this.back)
  30268. polygons = polygons.concat(this.back.allPolygons());
  30269. return polygons;
  30270. };
  30271. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30272. // new polygons are filtered down to the bottom of the tree and become new
  30273. // nodes there. Each set of polygons is partitioned using the first polygon
  30274. // (no heuristic is used to pick a good split).
  30275. Node.prototype.build = function (polygons) {
  30276. if (!polygons.length)
  30277. return;
  30278. if (!this.plane)
  30279. this.plane = polygons[0].plane.clone();
  30280. var front = [], back = [];
  30281. for (var i = 0; i < polygons.length; i++) {
  30282. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30283. }
  30284. if (front.length) {
  30285. if (!this.front)
  30286. this.front = new Node();
  30287. this.front.build(front);
  30288. }
  30289. if (back.length) {
  30290. if (!this.back)
  30291. this.back = new Node();
  30292. this.back.build(back);
  30293. }
  30294. };
  30295. return Node;
  30296. })();
  30297. var CSG = (function () {
  30298. function CSG() {
  30299. this.polygons = new Array();
  30300. }
  30301. // Convert BABYLON.Mesh to BABYLON.CSG
  30302. CSG.FromMesh = function (mesh) {
  30303. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30304. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30305. if (mesh instanceof BABYLON.Mesh) {
  30306. mesh.computeWorldMatrix(true);
  30307. matrix = mesh.getWorldMatrix();
  30308. meshPosition = mesh.position.clone();
  30309. meshRotation = mesh.rotation.clone();
  30310. if (mesh.rotationQuaternion) {
  30311. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30312. }
  30313. meshScaling = mesh.scaling.clone();
  30314. }
  30315. else {
  30316. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30317. }
  30318. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30319. var subMeshes = mesh.subMeshes;
  30320. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30321. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30322. vertices = [];
  30323. for (var j = 0; j < 3; j++) {
  30324. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30325. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30326. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30327. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30328. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30329. vertex = new Vertex(position, normal, uv);
  30330. vertices.push(vertex);
  30331. }
  30332. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30333. // To handle the case of degenerated triangle
  30334. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30335. if (polygon.plane)
  30336. polygons.push(polygon);
  30337. }
  30338. }
  30339. var csg = CSG.FromPolygons(polygons);
  30340. csg.matrix = matrix;
  30341. csg.position = meshPosition;
  30342. csg.rotation = meshRotation;
  30343. csg.scaling = meshScaling;
  30344. csg.rotationQuaternion = meshRotationQuaternion;
  30345. currentCSGMeshId++;
  30346. return csg;
  30347. };
  30348. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30349. CSG.FromPolygons = function (polygons) {
  30350. var csg = new CSG();
  30351. csg.polygons = polygons;
  30352. return csg;
  30353. };
  30354. CSG.prototype.clone = function () {
  30355. var csg = new CSG();
  30356. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30357. csg.copyTransformAttributes(this);
  30358. return csg;
  30359. };
  30360. CSG.prototype.toPolygons = function () {
  30361. return this.polygons;
  30362. };
  30363. CSG.prototype.union = function (csg) {
  30364. var a = new Node(this.clone().polygons);
  30365. var b = new Node(csg.clone().polygons);
  30366. a.clipTo(b);
  30367. b.clipTo(a);
  30368. b.invert();
  30369. b.clipTo(a);
  30370. b.invert();
  30371. a.build(b.allPolygons());
  30372. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30373. };
  30374. CSG.prototype.unionInPlace = function (csg) {
  30375. var a = new Node(this.polygons);
  30376. var b = new Node(csg.polygons);
  30377. a.clipTo(b);
  30378. b.clipTo(a);
  30379. b.invert();
  30380. b.clipTo(a);
  30381. b.invert();
  30382. a.build(b.allPolygons());
  30383. this.polygons = a.allPolygons();
  30384. };
  30385. CSG.prototype.subtract = function (csg) {
  30386. var a = new Node(this.clone().polygons);
  30387. var b = new Node(csg.clone().polygons);
  30388. a.invert();
  30389. a.clipTo(b);
  30390. b.clipTo(a);
  30391. b.invert();
  30392. b.clipTo(a);
  30393. b.invert();
  30394. a.build(b.allPolygons());
  30395. a.invert();
  30396. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30397. };
  30398. CSG.prototype.subtractInPlace = function (csg) {
  30399. var a = new Node(this.polygons);
  30400. var b = new Node(csg.polygons);
  30401. a.invert();
  30402. a.clipTo(b);
  30403. b.clipTo(a);
  30404. b.invert();
  30405. b.clipTo(a);
  30406. b.invert();
  30407. a.build(b.allPolygons());
  30408. a.invert();
  30409. this.polygons = a.allPolygons();
  30410. };
  30411. CSG.prototype.intersect = function (csg) {
  30412. var a = new Node(this.clone().polygons);
  30413. var b = new Node(csg.clone().polygons);
  30414. a.invert();
  30415. b.clipTo(a);
  30416. b.invert();
  30417. a.clipTo(b);
  30418. b.clipTo(a);
  30419. a.build(b.allPolygons());
  30420. a.invert();
  30421. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30422. };
  30423. CSG.prototype.intersectInPlace = function (csg) {
  30424. var a = new Node(this.polygons);
  30425. var b = new Node(csg.polygons);
  30426. a.invert();
  30427. b.clipTo(a);
  30428. b.invert();
  30429. a.clipTo(b);
  30430. b.clipTo(a);
  30431. a.build(b.allPolygons());
  30432. a.invert();
  30433. this.polygons = a.allPolygons();
  30434. };
  30435. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30436. // not modified.
  30437. CSG.prototype.inverse = function () {
  30438. var csg = this.clone();
  30439. csg.inverseInPlace();
  30440. return csg;
  30441. };
  30442. CSG.prototype.inverseInPlace = function () {
  30443. this.polygons.map(function (p) { p.flip(); });
  30444. };
  30445. // This is used to keep meshes transformations so they can be restored
  30446. // when we build back a Babylon Mesh
  30447. // NB : All CSG operations are performed in world coordinates
  30448. CSG.prototype.copyTransformAttributes = function (csg) {
  30449. this.matrix = csg.matrix;
  30450. this.position = csg.position;
  30451. this.rotation = csg.rotation;
  30452. this.scaling = csg.scaling;
  30453. this.rotationQuaternion = csg.rotationQuaternion;
  30454. return this;
  30455. };
  30456. // Build Raw mesh from CSG
  30457. // Coordinates here are in world space
  30458. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30459. var matrix = this.matrix.clone();
  30460. matrix.invert();
  30461. 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;
  30462. if (keepSubMeshes) {
  30463. // Sort Polygons, since subMeshes are indices range
  30464. polygons.sort(function (a, b) {
  30465. if (a.shared.meshId === b.shared.meshId) {
  30466. return a.shared.subMeshId - b.shared.subMeshId;
  30467. }
  30468. else {
  30469. return a.shared.meshId - b.shared.meshId;
  30470. }
  30471. });
  30472. }
  30473. for (var i = 0, il = polygons.length; i < il; i++) {
  30474. polygon = polygons[i];
  30475. // Building SubMeshes
  30476. if (!subMesh_dict[polygon.shared.meshId]) {
  30477. subMesh_dict[polygon.shared.meshId] = {};
  30478. }
  30479. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30480. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30481. indexStart: +Infinity,
  30482. indexEnd: -Infinity,
  30483. materialIndex: polygon.shared.materialIndex
  30484. };
  30485. }
  30486. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30487. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30488. polygonIndices[0] = 0;
  30489. polygonIndices[1] = j - 1;
  30490. polygonIndices[2] = j;
  30491. for (var k = 0; k < 3; k++) {
  30492. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30493. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30494. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30495. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30496. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30497. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30498. // Check if 2 points can be merged
  30499. if (!(typeof vertex_idx !== 'undefined' &&
  30500. normals[vertex_idx * 3] === localNormal.x &&
  30501. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30502. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30503. uvs[vertex_idx * 2] === uv.x &&
  30504. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30505. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30506. uvs.push(uv.x, uv.y);
  30507. normals.push(normal.x, normal.y, normal.z);
  30508. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30509. }
  30510. indices.push(vertex_idx);
  30511. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30512. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30513. currentIndex++;
  30514. }
  30515. }
  30516. }
  30517. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30518. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30519. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30520. mesh.setIndices(indices);
  30521. if (keepSubMeshes) {
  30522. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30523. var materialIndexOffset = 0, materialMaxIndex;
  30524. mesh.subMeshes = new Array();
  30525. for (var m in subMesh_dict) {
  30526. materialMaxIndex = -1;
  30527. for (var sm in subMesh_dict[m]) {
  30528. subMesh_obj = subMesh_dict[m][sm];
  30529. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30530. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30531. }
  30532. materialIndexOffset += ++materialMaxIndex;
  30533. }
  30534. }
  30535. return mesh;
  30536. };
  30537. // Build Mesh from CSG taking material and transforms into account
  30538. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30539. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30540. mesh.material = material;
  30541. mesh.position.copyFrom(this.position);
  30542. mesh.rotation.copyFrom(this.rotation);
  30543. if (this.rotationQuaternion) {
  30544. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30545. }
  30546. mesh.scaling.copyFrom(this.scaling);
  30547. mesh.computeWorldMatrix(true);
  30548. return mesh;
  30549. };
  30550. return CSG;
  30551. })();
  30552. BABYLON.CSG = CSG;
  30553. })(BABYLON || (BABYLON = {}));
  30554. var BABYLON;
  30555. (function (BABYLON) {
  30556. var VRDistortionCorrectionPostProcess = (function (_super) {
  30557. __extends(VRDistortionCorrectionPostProcess, _super);
  30558. //ANY
  30559. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30560. var _this = this;
  30561. _super.call(this, name, "vrDistortionCorrection", [
  30562. 'LensCenter',
  30563. 'Scale',
  30564. 'ScaleIn',
  30565. 'HmdWarpParam'
  30566. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30567. this._isRightEye = isRightEye;
  30568. this._distortionFactors = vrMetrics.distortionK;
  30569. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30570. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30571. this.onSizeChanged = function () {
  30572. _this.aspectRatio = _this.width * .5 / _this.height;
  30573. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30574. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30575. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30576. };
  30577. this.onApply = function (effect) {
  30578. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30579. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30580. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30581. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30582. };
  30583. }
  30584. return VRDistortionCorrectionPostProcess;
  30585. })(BABYLON.PostProcess);
  30586. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30587. })(BABYLON || (BABYLON = {}));
  30588. // Mainly based on these 2 articles :
  30589. // 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
  30590. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30591. var BABYLON;
  30592. (function (BABYLON) {
  30593. (function (JoystickAxis) {
  30594. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30595. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30596. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30597. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30598. var JoystickAxis = BABYLON.JoystickAxis;
  30599. var VirtualJoystick = (function () {
  30600. function VirtualJoystick(leftJoystick) {
  30601. var _this = this;
  30602. if (leftJoystick) {
  30603. this._leftJoystick = true;
  30604. }
  30605. else {
  30606. this._leftJoystick = false;
  30607. }
  30608. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30609. VirtualJoystick._globalJoystickIndex++;
  30610. // By default left & right arrow keys are moving the X
  30611. // and up & down keys are moving the Y
  30612. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30613. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30614. this.reverseLeftRight = false;
  30615. this.reverseUpDown = false;
  30616. // collections of pointers
  30617. this._touches = new BABYLON.SmartCollection();
  30618. this.deltaPosition = BABYLON.Vector3.Zero();
  30619. this._joystickSensibility = 25;
  30620. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30621. this._rotationSpeed = 25;
  30622. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30623. this._rotateOnAxisRelativeToMesh = false;
  30624. this._onResize = function (evt) {
  30625. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30626. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30627. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30628. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30629. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30630. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30631. };
  30632. // injecting a canvas element on top of the canvas 3D game
  30633. if (!VirtualJoystick.vjCanvas) {
  30634. window.addEventListener("resize", this._onResize, false);
  30635. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30636. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30637. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30638. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30639. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30640. VirtualJoystick.vjCanvas.style.width = "100%";
  30641. VirtualJoystick.vjCanvas.style.height = "100%";
  30642. VirtualJoystick.vjCanvas.style.position = "absolute";
  30643. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30644. VirtualJoystick.vjCanvas.style.top = "0px";
  30645. VirtualJoystick.vjCanvas.style.left = "0px";
  30646. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30647. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30648. // Support for jQuery PEP polyfill
  30649. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30650. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30651. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30652. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30653. document.body.appendChild(VirtualJoystick.vjCanvas);
  30654. }
  30655. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30656. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30657. this.pressed = false;
  30658. // default joystick color
  30659. this._joystickColor = "cyan";
  30660. this._joystickPointerID = -1;
  30661. // current joystick position
  30662. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30663. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30664. // origin joystick position
  30665. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30666. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30667. this._onPointerDownHandlerRef = function (evt) {
  30668. _this._onPointerDown(evt);
  30669. };
  30670. this._onPointerMoveHandlerRef = function (evt) {
  30671. _this._onPointerMove(evt);
  30672. };
  30673. this._onPointerOutHandlerRef = function (evt) {
  30674. _this._onPointerUp(evt);
  30675. };
  30676. this._onPointerUpHandlerRef = function (evt) {
  30677. _this._onPointerUp(evt);
  30678. };
  30679. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30680. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30681. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30682. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30683. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30684. evt.preventDefault(); // Disables system menu
  30685. }, false);
  30686. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30687. }
  30688. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30689. this._joystickSensibility = newJoystickSensibility;
  30690. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30691. };
  30692. VirtualJoystick.prototype._onPointerDown = function (e) {
  30693. var positionOnScreenCondition;
  30694. e.preventDefault();
  30695. if (this._leftJoystick === true) {
  30696. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30697. }
  30698. else {
  30699. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30700. }
  30701. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30702. // First contact will be dedicated to the virtual joystick
  30703. this._joystickPointerID = e.pointerId;
  30704. this._joystickPointerStartPos.x = e.clientX;
  30705. this._joystickPointerStartPos.y = e.clientY;
  30706. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30707. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30708. this._deltaJoystickVector.x = 0;
  30709. this._deltaJoystickVector.y = 0;
  30710. this.pressed = true;
  30711. this._touches.add(e.pointerId.toString(), e);
  30712. }
  30713. else {
  30714. // You can only trigger the action buttons with a joystick declared
  30715. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30716. this._action();
  30717. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30718. }
  30719. }
  30720. };
  30721. VirtualJoystick.prototype._onPointerMove = function (e) {
  30722. // If the current pointer is the one associated to the joystick (first touch contact)
  30723. if (this._joystickPointerID == e.pointerId) {
  30724. this._joystickPointerPos.x = e.clientX;
  30725. this._joystickPointerPos.y = e.clientY;
  30726. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30727. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30728. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30729. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30730. switch (this._axisTargetedByLeftAndRight) {
  30731. case JoystickAxis.X:
  30732. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30733. break;
  30734. case JoystickAxis.Y:
  30735. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30736. break;
  30737. case JoystickAxis.Z:
  30738. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30739. break;
  30740. }
  30741. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30742. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30743. switch (this._axisTargetedByUpAndDown) {
  30744. case JoystickAxis.X:
  30745. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30746. break;
  30747. case JoystickAxis.Y:
  30748. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30749. break;
  30750. case JoystickAxis.Z:
  30751. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30752. break;
  30753. }
  30754. }
  30755. else {
  30756. if (this._touches.item(e.pointerId.toString())) {
  30757. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30758. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30759. }
  30760. }
  30761. };
  30762. VirtualJoystick.prototype._onPointerUp = function (e) {
  30763. if (this._joystickPointerID == e.pointerId) {
  30764. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30765. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30766. this._joystickPointerID = -1;
  30767. this.pressed = false;
  30768. }
  30769. else {
  30770. var touch = this._touches.item(e.pointerId.toString());
  30771. if (touch) {
  30772. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30773. }
  30774. }
  30775. this._deltaJoystickVector.x = 0;
  30776. this._deltaJoystickVector.y = 0;
  30777. this._touches.remove(e.pointerId.toString());
  30778. };
  30779. /**
  30780. * Change the color of the virtual joystick
  30781. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30782. */
  30783. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30784. this._joystickColor = newColor;
  30785. };
  30786. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30787. this._action = action;
  30788. };
  30789. // Define which axis you'd like to control for left & right
  30790. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30791. switch (axis) {
  30792. case JoystickAxis.X:
  30793. case JoystickAxis.Y:
  30794. case JoystickAxis.Z:
  30795. this._axisTargetedByLeftAndRight = axis;
  30796. break;
  30797. default:
  30798. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30799. break;
  30800. }
  30801. };
  30802. // Define which axis you'd like to control for up & down
  30803. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30804. switch (axis) {
  30805. case JoystickAxis.X:
  30806. case JoystickAxis.Y:
  30807. case JoystickAxis.Z:
  30808. this._axisTargetedByUpAndDown = axis;
  30809. break;
  30810. default:
  30811. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30812. break;
  30813. }
  30814. };
  30815. VirtualJoystick.prototype._clearCanvas = function () {
  30816. if (this._leftJoystick) {
  30817. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30818. }
  30819. else {
  30820. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30821. }
  30822. };
  30823. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30824. var _this = this;
  30825. if (this.pressed) {
  30826. this._touches.forEach(function (touch) {
  30827. if (touch.pointerId === _this._joystickPointerID) {
  30828. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30829. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30830. VirtualJoystick.vjCanvasContext.beginPath();
  30831. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30832. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30833. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30834. VirtualJoystick.vjCanvasContext.stroke();
  30835. VirtualJoystick.vjCanvasContext.closePath();
  30836. VirtualJoystick.vjCanvasContext.beginPath();
  30837. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30838. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30839. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30840. VirtualJoystick.vjCanvasContext.stroke();
  30841. VirtualJoystick.vjCanvasContext.closePath();
  30842. VirtualJoystick.vjCanvasContext.beginPath();
  30843. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30844. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30845. VirtualJoystick.vjCanvasContext.stroke();
  30846. VirtualJoystick.vjCanvasContext.closePath();
  30847. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30848. }
  30849. else {
  30850. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30851. VirtualJoystick.vjCanvasContext.beginPath();
  30852. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30853. VirtualJoystick.vjCanvasContext.beginPath();
  30854. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30855. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30856. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30857. VirtualJoystick.vjCanvasContext.stroke();
  30858. VirtualJoystick.vjCanvasContext.closePath();
  30859. touch.prevX = touch.x;
  30860. touch.prevY = touch.y;
  30861. }
  30862. ;
  30863. });
  30864. }
  30865. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30866. };
  30867. VirtualJoystick.prototype.releaseCanvas = function () {
  30868. if (VirtualJoystick.vjCanvas) {
  30869. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30870. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30871. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30872. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30873. window.removeEventListener("resize", this._onResize);
  30874. document.body.removeChild(VirtualJoystick.vjCanvas);
  30875. VirtualJoystick.vjCanvas = null;
  30876. }
  30877. };
  30878. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30879. VirtualJoystick._globalJoystickIndex = 0;
  30880. return VirtualJoystick;
  30881. })();
  30882. BABYLON.VirtualJoystick = VirtualJoystick;
  30883. })(BABYLON || (BABYLON = {}));
  30884. var BABYLON;
  30885. (function (BABYLON) {
  30886. // We're mainly based on the logic defined into the FreeCamera code
  30887. var VirtualJoysticksCamera = (function (_super) {
  30888. __extends(VirtualJoysticksCamera, _super);
  30889. function VirtualJoysticksCamera(name, position, scene) {
  30890. _super.call(this, name, position, scene);
  30891. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30892. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30893. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30894. this._leftjoystick.setJoystickSensibility(0.15);
  30895. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30896. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30897. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30898. this._rightjoystick.reverseUpDown = true;
  30899. this._rightjoystick.setJoystickSensibility(0.05);
  30900. this._rightjoystick.setJoystickColor("yellow");
  30901. }
  30902. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30903. return this._leftjoystick;
  30904. };
  30905. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30906. return this._rightjoystick;
  30907. };
  30908. VirtualJoysticksCamera.prototype._checkInputs = function () {
  30909. var speed = this._computeLocalCameraSpeed() * 50;
  30910. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  30911. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  30912. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  30913. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  30914. if (!this._leftjoystick.pressed) {
  30915. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  30916. }
  30917. if (!this._rightjoystick.pressed) {
  30918. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  30919. }
  30920. _super.prototype._checkInputs.call(this);
  30921. };
  30922. VirtualJoysticksCamera.prototype.dispose = function () {
  30923. this._leftjoystick.releaseCanvas();
  30924. _super.prototype.dispose.call(this);
  30925. };
  30926. return VirtualJoysticksCamera;
  30927. })(BABYLON.FreeCamera);
  30928. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  30929. })(BABYLON || (BABYLON = {}));
  30930. var BABYLON;
  30931. (function (BABYLON) {
  30932. var AnaglyphPostProcess = (function (_super) {
  30933. __extends(AnaglyphPostProcess, _super);
  30934. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30935. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  30936. }
  30937. return AnaglyphPostProcess;
  30938. })(BABYLON.PostProcess);
  30939. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  30940. })(BABYLON || (BABYLON = {}));
  30941. var BABYLON;
  30942. (function (BABYLON) {
  30943. var OutlineRenderer = (function () {
  30944. function OutlineRenderer(scene) {
  30945. this._scene = scene;
  30946. }
  30947. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  30948. var _this = this;
  30949. if (useOverlay === void 0) { useOverlay = false; }
  30950. var scene = this._scene;
  30951. var engine = this._scene.getEngine();
  30952. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  30953. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  30954. return;
  30955. }
  30956. var mesh = subMesh.getRenderingMesh();
  30957. var material = subMesh.getMaterial();
  30958. engine.enableEffect(this._effect);
  30959. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  30960. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  30961. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30962. // Bones
  30963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30964. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30965. }
  30966. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  30967. // Alpha test
  30968. if (material && material.needAlphaTesting()) {
  30969. var alphaTexture = material.getAlphaTestTexture();
  30970. this._effect.setTexture("diffuseSampler", alphaTexture);
  30971. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30972. }
  30973. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  30974. };
  30975. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  30976. var defines = [];
  30977. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  30978. var mesh = subMesh.getMesh();
  30979. var material = subMesh.getMaterial();
  30980. // Alpha test
  30981. if (material && material.needAlphaTesting()) {
  30982. defines.push("#define ALPHATEST");
  30983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30984. attribs.push(BABYLON.VertexBuffer.UVKind);
  30985. defines.push("#define UV1");
  30986. }
  30987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30988. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30989. defines.push("#define UV2");
  30990. }
  30991. }
  30992. // Bones
  30993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30996. defines.push("#define BONES");
  30997. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30998. }
  30999. // Instances
  31000. if (useInstances) {
  31001. defines.push("#define INSTANCES");
  31002. attribs.push("world0");
  31003. attribs.push("world1");
  31004. attribs.push("world2");
  31005. attribs.push("world3");
  31006. }
  31007. // Get correct effect
  31008. var join = defines.join("\n");
  31009. if (this._cachedDefines !== join) {
  31010. this._cachedDefines = join;
  31011. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31012. }
  31013. return this._effect.isReady();
  31014. };
  31015. return OutlineRenderer;
  31016. })();
  31017. BABYLON.OutlineRenderer = OutlineRenderer;
  31018. })(BABYLON || (BABYLON = {}));
  31019. var BABYLON;
  31020. (function (BABYLON) {
  31021. var MeshAssetTask = (function () {
  31022. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31023. this.name = name;
  31024. this.meshesNames = meshesNames;
  31025. this.rootUrl = rootUrl;
  31026. this.sceneFilename = sceneFilename;
  31027. this.isCompleted = false;
  31028. }
  31029. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31030. var _this = this;
  31031. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31032. _this.loadedMeshes = meshes;
  31033. _this.loadedParticleSystems = particleSystems;
  31034. _this.loadedSkeletons = skeletons;
  31035. _this.isCompleted = true;
  31036. if (_this.onSuccess) {
  31037. _this.onSuccess(_this);
  31038. }
  31039. onSuccess();
  31040. }, null, function () {
  31041. if (_this.onError) {
  31042. _this.onError(_this);
  31043. }
  31044. onError();
  31045. });
  31046. };
  31047. return MeshAssetTask;
  31048. })();
  31049. BABYLON.MeshAssetTask = MeshAssetTask;
  31050. var TextFileAssetTask = (function () {
  31051. function TextFileAssetTask(name, url) {
  31052. this.name = name;
  31053. this.url = url;
  31054. this.isCompleted = false;
  31055. }
  31056. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31057. var _this = this;
  31058. BABYLON.Tools.LoadFile(this.url, function (data) {
  31059. _this.text = data;
  31060. _this.isCompleted = true;
  31061. if (_this.onSuccess) {
  31062. _this.onSuccess(_this);
  31063. }
  31064. onSuccess();
  31065. }, null, scene.database, false, function () {
  31066. if (_this.onError) {
  31067. _this.onError(_this);
  31068. }
  31069. onError();
  31070. });
  31071. };
  31072. return TextFileAssetTask;
  31073. })();
  31074. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31075. var BinaryFileAssetTask = (function () {
  31076. function BinaryFileAssetTask(name, url) {
  31077. this.name = name;
  31078. this.url = url;
  31079. this.isCompleted = false;
  31080. }
  31081. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31082. var _this = this;
  31083. BABYLON.Tools.LoadFile(this.url, function (data) {
  31084. _this.data = data;
  31085. _this.isCompleted = true;
  31086. if (_this.onSuccess) {
  31087. _this.onSuccess(_this);
  31088. }
  31089. onSuccess();
  31090. }, null, scene.database, true, function () {
  31091. if (_this.onError) {
  31092. _this.onError(_this);
  31093. }
  31094. onError();
  31095. });
  31096. };
  31097. return BinaryFileAssetTask;
  31098. })();
  31099. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31100. var ImageAssetTask = (function () {
  31101. function ImageAssetTask(name, url) {
  31102. this.name = name;
  31103. this.url = url;
  31104. this.isCompleted = false;
  31105. }
  31106. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31107. var _this = this;
  31108. var img = new Image();
  31109. img.onload = function () {
  31110. _this.image = img;
  31111. _this.isCompleted = true;
  31112. if (_this.onSuccess) {
  31113. _this.onSuccess(_this);
  31114. }
  31115. onSuccess();
  31116. };
  31117. img.onerror = function () {
  31118. if (_this.onError) {
  31119. _this.onError(_this);
  31120. }
  31121. onError();
  31122. };
  31123. img.src = this.url;
  31124. };
  31125. return ImageAssetTask;
  31126. })();
  31127. BABYLON.ImageAssetTask = ImageAssetTask;
  31128. var TextureAssetTask = (function () {
  31129. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31130. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31131. this.name = name;
  31132. this.url = url;
  31133. this.noMipmap = noMipmap;
  31134. this.invertY = invertY;
  31135. this.samplingMode = samplingMode;
  31136. this.isCompleted = false;
  31137. }
  31138. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31139. var _this = this;
  31140. var onload = function () {
  31141. _this.isCompleted = true;
  31142. if (_this.onSuccess) {
  31143. _this.onSuccess(_this);
  31144. }
  31145. onSuccess();
  31146. };
  31147. var onerror = function () {
  31148. if (_this.onError) {
  31149. _this.onError(_this);
  31150. }
  31151. onError();
  31152. };
  31153. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31154. };
  31155. return TextureAssetTask;
  31156. })();
  31157. BABYLON.TextureAssetTask = TextureAssetTask;
  31158. var AssetsManager = (function () {
  31159. function AssetsManager(scene) {
  31160. this._tasks = new Array();
  31161. this._waitingTasksCount = 0;
  31162. this.useDefaultLoadingScreen = true;
  31163. this._scene = scene;
  31164. }
  31165. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31166. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31167. this._tasks.push(task);
  31168. return task;
  31169. };
  31170. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31171. var task = new TextFileAssetTask(taskName, url);
  31172. this._tasks.push(task);
  31173. return task;
  31174. };
  31175. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31176. var task = new BinaryFileAssetTask(taskName, url);
  31177. this._tasks.push(task);
  31178. return task;
  31179. };
  31180. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31181. var task = new ImageAssetTask(taskName, url);
  31182. this._tasks.push(task);
  31183. return task;
  31184. };
  31185. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31187. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31188. this._tasks.push(task);
  31189. return task;
  31190. };
  31191. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31192. this._waitingTasksCount--;
  31193. if (this._waitingTasksCount === 0) {
  31194. if (this.onFinish) {
  31195. this.onFinish(this._tasks);
  31196. }
  31197. this._scene.getEngine().hideLoadingUI();
  31198. }
  31199. };
  31200. AssetsManager.prototype._runTask = function (task) {
  31201. var _this = this;
  31202. task.run(this._scene, function () {
  31203. if (_this.onTaskSuccess) {
  31204. _this.onTaskSuccess(task);
  31205. }
  31206. _this._decreaseWaitingTasksCount();
  31207. }, function () {
  31208. if (_this.onTaskError) {
  31209. _this.onTaskError(task);
  31210. }
  31211. _this._decreaseWaitingTasksCount();
  31212. });
  31213. };
  31214. AssetsManager.prototype.reset = function () {
  31215. this._tasks = new Array();
  31216. return this;
  31217. };
  31218. AssetsManager.prototype.load = function () {
  31219. this._waitingTasksCount = this._tasks.length;
  31220. if (this._waitingTasksCount === 0) {
  31221. if (this.onFinish) {
  31222. this.onFinish(this._tasks);
  31223. }
  31224. return this;
  31225. }
  31226. if (this.useDefaultLoadingScreen) {
  31227. this._scene.getEngine().displayLoadingUI();
  31228. }
  31229. for (var index = 0; index < this._tasks.length; index++) {
  31230. var task = this._tasks[index];
  31231. this._runTask(task);
  31232. }
  31233. return this;
  31234. };
  31235. return AssetsManager;
  31236. })();
  31237. BABYLON.AssetsManager = AssetsManager;
  31238. })(BABYLON || (BABYLON = {}));
  31239. var BABYLON;
  31240. (function (BABYLON) {
  31241. var VRDeviceOrientationFreeCamera = (function (_super) {
  31242. __extends(VRDeviceOrientationFreeCamera, _super);
  31243. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31244. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31245. _super.call(this, name, position, scene);
  31246. this._alpha = 0;
  31247. this._beta = 0;
  31248. this._gamma = 0;
  31249. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31250. metrics.compensateDistortion = compensateDistortion;
  31251. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31252. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31253. }
  31254. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31255. this._alpha = +evt.alpha | 0;
  31256. this._beta = +evt.beta | 0;
  31257. this._gamma = +evt.gamma | 0;
  31258. if (this._gamma < 0) {
  31259. this._gamma = 90 + this._gamma;
  31260. }
  31261. else {
  31262. // Incline it in the correct angle.
  31263. this._gamma = 270 - this._gamma;
  31264. }
  31265. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31266. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31267. this.rotation.z = this._beta / 180.0 * Math.PI;
  31268. };
  31269. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31270. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31271. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31272. };
  31273. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31274. _super.prototype.detachControl.call(this, element);
  31275. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31276. };
  31277. return VRDeviceOrientationFreeCamera;
  31278. })(BABYLON.FreeCamera);
  31279. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31280. })(BABYLON || (BABYLON = {}));
  31281. var BABYLON;
  31282. (function (BABYLON) {
  31283. var WebVRFreeCamera = (function (_super) {
  31284. __extends(WebVRFreeCamera, _super);
  31285. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31286. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31287. _super.call(this, name, position, scene);
  31288. this._hmdDevice = null;
  31289. this._sensorDevice = null;
  31290. this._cacheState = null;
  31291. this._cacheQuaternion = new BABYLON.Quaternion();
  31292. this._cacheRotation = BABYLON.Vector3.Zero();
  31293. this._vrEnabled = false;
  31294. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31295. metrics.compensateDistortion = compensateDistortion;
  31296. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31297. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31298. }
  31299. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31300. var size = devices.length;
  31301. var i = 0;
  31302. // Reset devices.
  31303. this._sensorDevice = null;
  31304. this._hmdDevice = null;
  31305. // Search for a HmdDevice.
  31306. while (i < size && this._hmdDevice === null) {
  31307. if (devices[i] instanceof HMDVRDevice) {
  31308. this._hmdDevice = devices[i];
  31309. }
  31310. i++;
  31311. }
  31312. i = 0;
  31313. while (i < size && this._sensorDevice === null) {
  31314. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31315. this._sensorDevice = devices[i];
  31316. }
  31317. i++;
  31318. }
  31319. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31320. };
  31321. WebVRFreeCamera.prototype._checkInputs = function () {
  31322. if (this._vrEnabled) {
  31323. this._cacheState = this._sensorDevice.getState();
  31324. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31325. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31326. this.rotation.x = -this._cacheRotation.z;
  31327. this.rotation.y = -this._cacheRotation.y;
  31328. this.rotation.z = this._cacheRotation.x;
  31329. }
  31330. _super.prototype._checkInputs.call(this);
  31331. };
  31332. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31333. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31334. if (navigator.getVRDevices) {
  31335. navigator.getVRDevices().then(this._getWebVRDevices);
  31336. }
  31337. else if (navigator.mozGetVRDevices) {
  31338. navigator.mozGetVRDevices(this._getWebVRDevices);
  31339. }
  31340. };
  31341. WebVRFreeCamera.prototype.detachControl = function (element) {
  31342. _super.prototype.detachControl.call(this, element);
  31343. this._vrEnabled = false;
  31344. };
  31345. return WebVRFreeCamera;
  31346. })(BABYLON.FreeCamera);
  31347. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31348. })(BABYLON || (BABYLON = {}));
  31349. var BABYLON;
  31350. (function (BABYLON) {
  31351. // Standard optimizations
  31352. var SceneOptimization = (function () {
  31353. function SceneOptimization(priority) {
  31354. if (priority === void 0) { priority = 0; }
  31355. this.priority = priority;
  31356. this.apply = function (scene) {
  31357. return true; // Return true if everything that can be done was applied
  31358. };
  31359. }
  31360. return SceneOptimization;
  31361. })();
  31362. BABYLON.SceneOptimization = SceneOptimization;
  31363. var TextureOptimization = (function (_super) {
  31364. __extends(TextureOptimization, _super);
  31365. function TextureOptimization(priority, maximumSize) {
  31366. var _this = this;
  31367. if (priority === void 0) { priority = 0; }
  31368. if (maximumSize === void 0) { maximumSize = 1024; }
  31369. _super.call(this, priority);
  31370. this.priority = priority;
  31371. this.maximumSize = maximumSize;
  31372. this.apply = function (scene) {
  31373. var allDone = true;
  31374. for (var index = 0; index < scene.textures.length; index++) {
  31375. var texture = scene.textures[index];
  31376. if (!texture.canRescale) {
  31377. continue;
  31378. }
  31379. var currentSize = texture.getSize();
  31380. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31381. if (maxDimension > _this.maximumSize) {
  31382. texture.scale(0.5);
  31383. allDone = false;
  31384. }
  31385. }
  31386. return allDone;
  31387. };
  31388. }
  31389. return TextureOptimization;
  31390. })(SceneOptimization);
  31391. BABYLON.TextureOptimization = TextureOptimization;
  31392. var HardwareScalingOptimization = (function (_super) {
  31393. __extends(HardwareScalingOptimization, _super);
  31394. function HardwareScalingOptimization(priority, maximumScale) {
  31395. var _this = this;
  31396. if (priority === void 0) { priority = 0; }
  31397. if (maximumScale === void 0) { maximumScale = 2; }
  31398. _super.call(this, priority);
  31399. this.priority = priority;
  31400. this.maximumScale = maximumScale;
  31401. this._currentScale = 1;
  31402. this.apply = function (scene) {
  31403. _this._currentScale++;
  31404. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31405. return _this._currentScale >= _this.maximumScale;
  31406. };
  31407. }
  31408. return HardwareScalingOptimization;
  31409. })(SceneOptimization);
  31410. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31411. var ShadowsOptimization = (function (_super) {
  31412. __extends(ShadowsOptimization, _super);
  31413. function ShadowsOptimization() {
  31414. _super.apply(this, arguments);
  31415. this.apply = function (scene) {
  31416. scene.shadowsEnabled = false;
  31417. return true;
  31418. };
  31419. }
  31420. return ShadowsOptimization;
  31421. })(SceneOptimization);
  31422. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31423. var PostProcessesOptimization = (function (_super) {
  31424. __extends(PostProcessesOptimization, _super);
  31425. function PostProcessesOptimization() {
  31426. _super.apply(this, arguments);
  31427. this.apply = function (scene) {
  31428. scene.postProcessesEnabled = false;
  31429. return true;
  31430. };
  31431. }
  31432. return PostProcessesOptimization;
  31433. })(SceneOptimization);
  31434. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31435. var LensFlaresOptimization = (function (_super) {
  31436. __extends(LensFlaresOptimization, _super);
  31437. function LensFlaresOptimization() {
  31438. _super.apply(this, arguments);
  31439. this.apply = function (scene) {
  31440. scene.lensFlaresEnabled = false;
  31441. return true;
  31442. };
  31443. }
  31444. return LensFlaresOptimization;
  31445. })(SceneOptimization);
  31446. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31447. var ParticlesOptimization = (function (_super) {
  31448. __extends(ParticlesOptimization, _super);
  31449. function ParticlesOptimization() {
  31450. _super.apply(this, arguments);
  31451. this.apply = function (scene) {
  31452. scene.particlesEnabled = false;
  31453. return true;
  31454. };
  31455. }
  31456. return ParticlesOptimization;
  31457. })(SceneOptimization);
  31458. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31459. var RenderTargetsOptimization = (function (_super) {
  31460. __extends(RenderTargetsOptimization, _super);
  31461. function RenderTargetsOptimization() {
  31462. _super.apply(this, arguments);
  31463. this.apply = function (scene) {
  31464. scene.renderTargetsEnabled = false;
  31465. return true;
  31466. };
  31467. }
  31468. return RenderTargetsOptimization;
  31469. })(SceneOptimization);
  31470. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31471. var MergeMeshesOptimization = (function (_super) {
  31472. __extends(MergeMeshesOptimization, _super);
  31473. function MergeMeshesOptimization() {
  31474. var _this = this;
  31475. _super.apply(this, arguments);
  31476. this._canBeMerged = function (abstractMesh) {
  31477. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31478. return false;
  31479. }
  31480. var mesh = abstractMesh;
  31481. if (!mesh.isVisible || !mesh.isEnabled()) {
  31482. return false;
  31483. }
  31484. if (mesh.instances.length > 0) {
  31485. return false;
  31486. }
  31487. if (mesh.skeleton || mesh.hasLODLevels) {
  31488. return false;
  31489. }
  31490. return true;
  31491. };
  31492. this.apply = function (scene, updateSelectionTree) {
  31493. var globalPool = scene.meshes.slice(0);
  31494. var globalLength = globalPool.length;
  31495. for (var index = 0; index < globalLength; index++) {
  31496. var currentPool = new Array();
  31497. var current = globalPool[index];
  31498. // Checks
  31499. if (!_this._canBeMerged(current)) {
  31500. continue;
  31501. }
  31502. currentPool.push(current);
  31503. // Find compatible meshes
  31504. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31505. var otherMesh = globalPool[subIndex];
  31506. if (!_this._canBeMerged(otherMesh)) {
  31507. continue;
  31508. }
  31509. if (otherMesh.material !== current.material) {
  31510. continue;
  31511. }
  31512. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31513. continue;
  31514. }
  31515. currentPool.push(otherMesh);
  31516. globalLength--;
  31517. globalPool.splice(subIndex, 1);
  31518. subIndex--;
  31519. }
  31520. if (currentPool.length < 2) {
  31521. continue;
  31522. }
  31523. // Merge meshes
  31524. BABYLON.Mesh.MergeMeshes(currentPool);
  31525. }
  31526. if (updateSelectionTree != undefined) {
  31527. if (updateSelectionTree) {
  31528. scene.createOrUpdateSelectionOctree();
  31529. }
  31530. }
  31531. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31532. scene.createOrUpdateSelectionOctree();
  31533. }
  31534. return true;
  31535. };
  31536. }
  31537. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31538. get: function () {
  31539. return MergeMeshesOptimization._UpdateSelectionTree;
  31540. },
  31541. set: function (value) {
  31542. MergeMeshesOptimization._UpdateSelectionTree = value;
  31543. },
  31544. enumerable: true,
  31545. configurable: true
  31546. });
  31547. MergeMeshesOptimization._UpdateSelectionTree = false;
  31548. return MergeMeshesOptimization;
  31549. })(SceneOptimization);
  31550. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31551. // Options
  31552. var SceneOptimizerOptions = (function () {
  31553. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31554. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31555. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31556. this.targetFrameRate = targetFrameRate;
  31557. this.trackerDuration = trackerDuration;
  31558. this.optimizations = new Array();
  31559. }
  31560. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31561. var result = new SceneOptimizerOptions(targetFrameRate);
  31562. var priority = 0;
  31563. result.optimizations.push(new MergeMeshesOptimization(priority));
  31564. result.optimizations.push(new ShadowsOptimization(priority));
  31565. result.optimizations.push(new LensFlaresOptimization(priority));
  31566. // Next priority
  31567. priority++;
  31568. result.optimizations.push(new PostProcessesOptimization(priority));
  31569. result.optimizations.push(new ParticlesOptimization(priority));
  31570. // Next priority
  31571. priority++;
  31572. result.optimizations.push(new TextureOptimization(priority, 1024));
  31573. return result;
  31574. };
  31575. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31576. var result = new SceneOptimizerOptions(targetFrameRate);
  31577. var priority = 0;
  31578. result.optimizations.push(new MergeMeshesOptimization(priority));
  31579. result.optimizations.push(new ShadowsOptimization(priority));
  31580. result.optimizations.push(new LensFlaresOptimization(priority));
  31581. // Next priority
  31582. priority++;
  31583. result.optimizations.push(new PostProcessesOptimization(priority));
  31584. result.optimizations.push(new ParticlesOptimization(priority));
  31585. // Next priority
  31586. priority++;
  31587. result.optimizations.push(new TextureOptimization(priority, 512));
  31588. // Next priority
  31589. priority++;
  31590. result.optimizations.push(new RenderTargetsOptimization(priority));
  31591. // Next priority
  31592. priority++;
  31593. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31594. return result;
  31595. };
  31596. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31597. var result = new SceneOptimizerOptions(targetFrameRate);
  31598. var priority = 0;
  31599. result.optimizations.push(new MergeMeshesOptimization(priority));
  31600. result.optimizations.push(new ShadowsOptimization(priority));
  31601. result.optimizations.push(new LensFlaresOptimization(priority));
  31602. // Next priority
  31603. priority++;
  31604. result.optimizations.push(new PostProcessesOptimization(priority));
  31605. result.optimizations.push(new ParticlesOptimization(priority));
  31606. // Next priority
  31607. priority++;
  31608. result.optimizations.push(new TextureOptimization(priority, 256));
  31609. // Next priority
  31610. priority++;
  31611. result.optimizations.push(new RenderTargetsOptimization(priority));
  31612. // Next priority
  31613. priority++;
  31614. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31615. return result;
  31616. };
  31617. return SceneOptimizerOptions;
  31618. })();
  31619. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31620. // Scene optimizer tool
  31621. var SceneOptimizer = (function () {
  31622. function SceneOptimizer() {
  31623. }
  31624. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31625. // TODO: add an epsilon
  31626. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31627. if (onSuccess) {
  31628. onSuccess();
  31629. }
  31630. return;
  31631. }
  31632. // Apply current level of optimizations
  31633. var allDone = true;
  31634. var noOptimizationApplied = true;
  31635. for (var index = 0; index < options.optimizations.length; index++) {
  31636. var optimization = options.optimizations[index];
  31637. if (optimization.priority === currentPriorityLevel) {
  31638. noOptimizationApplied = false;
  31639. allDone = allDone && optimization.apply(scene);
  31640. }
  31641. }
  31642. // If no optimization was applied, this is a failure :(
  31643. if (noOptimizationApplied) {
  31644. if (onFailure) {
  31645. onFailure();
  31646. }
  31647. return;
  31648. }
  31649. // If all optimizations were done, move to next level
  31650. if (allDone) {
  31651. currentPriorityLevel++;
  31652. }
  31653. // Let's the system running for a specific amount of time before checking FPS
  31654. scene.executeWhenReady(function () {
  31655. setTimeout(function () {
  31656. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31657. }, options.trackerDuration);
  31658. });
  31659. };
  31660. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31661. if (!options) {
  31662. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31663. }
  31664. // Let's the system running for a specific amount of time before checking FPS
  31665. scene.executeWhenReady(function () {
  31666. setTimeout(function () {
  31667. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31668. }, options.trackerDuration);
  31669. });
  31670. };
  31671. return SceneOptimizer;
  31672. })();
  31673. BABYLON.SceneOptimizer = SceneOptimizer;
  31674. })(BABYLON || (BABYLON = {}));
  31675. var BABYLON;
  31676. (function (BABYLON) {
  31677. var Internals;
  31678. (function (Internals) {
  31679. var MeshLODLevel = (function () {
  31680. function MeshLODLevel(distance, mesh) {
  31681. this.distance = distance;
  31682. this.mesh = mesh;
  31683. }
  31684. return MeshLODLevel;
  31685. })();
  31686. Internals.MeshLODLevel = MeshLODLevel;
  31687. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31688. })(BABYLON || (BABYLON = {}));
  31689. var BABYLON;
  31690. (function (BABYLON) {
  31691. var RawTexture = (function (_super) {
  31692. __extends(RawTexture, _super);
  31693. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31694. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31695. if (invertY === void 0) { invertY = false; }
  31696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31697. _super.call(this, null, scene, !generateMipMaps, invertY);
  31698. this.format = format;
  31699. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31700. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31701. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31702. }
  31703. RawTexture.prototype.update = function (data) {
  31704. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31705. };
  31706. // Statics
  31707. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31708. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31709. if (invertY === void 0) { invertY = false; }
  31710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31711. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31712. };
  31713. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31714. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31715. if (invertY === void 0) { invertY = false; }
  31716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31717. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31718. };
  31719. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31720. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31721. if (invertY === void 0) { invertY = false; }
  31722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31723. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31724. };
  31725. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31726. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31727. if (invertY === void 0) { invertY = false; }
  31728. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31729. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31730. };
  31731. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31732. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31733. if (invertY === void 0) { invertY = false; }
  31734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31735. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31736. };
  31737. return RawTexture;
  31738. })(BABYLON.Texture);
  31739. BABYLON.RawTexture = RawTexture;
  31740. })(BABYLON || (BABYLON = {}));
  31741. var BABYLON;
  31742. (function (BABYLON) {
  31743. var IndexedVector2 = (function (_super) {
  31744. __extends(IndexedVector2, _super);
  31745. function IndexedVector2(original, index) {
  31746. _super.call(this, original.x, original.y);
  31747. this.index = index;
  31748. }
  31749. return IndexedVector2;
  31750. })(BABYLON.Vector2);
  31751. var PolygonPoints = (function () {
  31752. function PolygonPoints() {
  31753. this.elements = new Array();
  31754. }
  31755. PolygonPoints.prototype.add = function (originalPoints) {
  31756. var _this = this;
  31757. var result = new Array();
  31758. originalPoints.forEach(function (point) {
  31759. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31760. var newPoint = new IndexedVector2(point, _this.elements.length);
  31761. result.push(newPoint);
  31762. _this.elements.push(newPoint);
  31763. }
  31764. });
  31765. return result;
  31766. };
  31767. PolygonPoints.prototype.computeBounds = function () {
  31768. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31769. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31770. this.elements.forEach(function (point) {
  31771. // x
  31772. if (point.x < lmin.x) {
  31773. lmin.x = point.x;
  31774. }
  31775. else if (point.x > lmax.x) {
  31776. lmax.x = point.x;
  31777. }
  31778. // y
  31779. if (point.y < lmin.y) {
  31780. lmin.y = point.y;
  31781. }
  31782. else if (point.y > lmax.y) {
  31783. lmax.y = point.y;
  31784. }
  31785. });
  31786. return {
  31787. min: lmin,
  31788. max: lmax,
  31789. width: lmax.x - lmin.x,
  31790. height: lmax.y - lmin.y
  31791. };
  31792. };
  31793. return PolygonPoints;
  31794. })();
  31795. var Polygon = (function () {
  31796. function Polygon() {
  31797. }
  31798. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31799. return [
  31800. new BABYLON.Vector2(xmin, ymin),
  31801. new BABYLON.Vector2(xmax, ymin),
  31802. new BABYLON.Vector2(xmax, ymax),
  31803. new BABYLON.Vector2(xmin, ymax)
  31804. ];
  31805. };
  31806. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31807. if (cx === void 0) { cx = 0; }
  31808. if (cy === void 0) { cy = 0; }
  31809. if (numberOfSides === void 0) { numberOfSides = 32; }
  31810. var result = new Array();
  31811. var angle = 0;
  31812. var increment = (Math.PI * 2) / numberOfSides;
  31813. for (var i = 0; i < numberOfSides; i++) {
  31814. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31815. angle -= increment;
  31816. }
  31817. return result;
  31818. };
  31819. Polygon.Parse = function (input) {
  31820. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31821. var i, result = [];
  31822. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31823. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31824. }
  31825. return result;
  31826. };
  31827. Polygon.StartingAt = function (x, y) {
  31828. return BABYLON.Path2.StartingAt(x, y);
  31829. };
  31830. return Polygon;
  31831. })();
  31832. BABYLON.Polygon = Polygon;
  31833. var PolygonMeshBuilder = (function () {
  31834. function PolygonMeshBuilder(name, contours, scene) {
  31835. this._points = new PolygonPoints();
  31836. this._outlinepoints = new PolygonPoints();
  31837. this._holes = [];
  31838. if (!("poly2tri" in window)) {
  31839. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31840. }
  31841. this._name = name;
  31842. this._scene = scene;
  31843. var points;
  31844. if (contours instanceof BABYLON.Path2) {
  31845. points = contours.getPoints();
  31846. }
  31847. else {
  31848. points = contours;
  31849. }
  31850. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31851. this._outlinepoints.add(points);
  31852. }
  31853. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31854. this._swctx.addHole(this._points.add(hole));
  31855. var holepoints = new PolygonPoints();
  31856. holepoints.add(hole);
  31857. this._holes.push(holepoints);
  31858. return this;
  31859. };
  31860. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31861. var _this = this;
  31862. if (updatable === void 0) { updatable = false; }
  31863. var result = new BABYLON.Mesh(this._name, this._scene);
  31864. var normals = [];
  31865. var positions = [];
  31866. var uvs = [];
  31867. var bounds = this._points.computeBounds();
  31868. this._points.elements.forEach(function (p) {
  31869. normals.push(0, 1.0, 0);
  31870. positions.push(p.x, 0, p.y);
  31871. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31872. });
  31873. var indices = [];
  31874. this._swctx.triangulate();
  31875. this._swctx.getTriangles().forEach(function (triangle) {
  31876. triangle.getPoints().forEach(function (point) {
  31877. indices.push(point.index);
  31878. });
  31879. });
  31880. if (depth > 0) {
  31881. var positionscount = (positions.length / 3); //get the current pointcount
  31882. this._points.elements.forEach(function (p) {
  31883. normals.push(0, -1.0, 0);
  31884. positions.push(p.x, -depth, p.y);
  31885. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31886. });
  31887. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31888. var p2;
  31889. var poscounter = 0;
  31890. this._swctx.getTriangles().forEach(function (triangle) {
  31891. triangle.getPoints().forEach(function (point) {
  31892. switch (poscounter) {
  31893. case 0:
  31894. p1 = point;
  31895. break;
  31896. case 1:
  31897. p2 = point;
  31898. break;
  31899. case 2:
  31900. indices.push(point.index + positionscount);
  31901. indices.push(p2.index + positionscount);
  31902. indices.push(p1.index + positionscount);
  31903. poscounter = -1;
  31904. break;
  31905. }
  31906. poscounter++;
  31907. //indices.push((<IndexedVector2>point).index + positionscount);
  31908. });
  31909. });
  31910. //Add the sides
  31911. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31912. this._holes.forEach(function (hole) {
  31913. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31914. });
  31915. }
  31916. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31917. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31918. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31919. result.setIndices(indices);
  31920. return result;
  31921. };
  31922. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31923. var StartIndex = positions.length / 3;
  31924. var ulength = 0;
  31925. for (var i = 0; i < points.elements.length; i++) {
  31926. var p = points.elements[i];
  31927. var p1;
  31928. if ((i + 1) > points.elements.length - 1) {
  31929. p1 = points.elements[0];
  31930. }
  31931. else {
  31932. p1 = points.elements[i + 1];
  31933. }
  31934. positions.push(p.x, 0, p.y);
  31935. positions.push(p.x, -depth, p.y);
  31936. positions.push(p1.x, 0, p1.y);
  31937. positions.push(p1.x, -depth, p1.y);
  31938. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31939. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31940. var v3 = v2.subtract(v1);
  31941. var v4 = new BABYLON.Vector3(0, 1, 0);
  31942. var vn = BABYLON.Vector3.Cross(v3, v4);
  31943. vn = vn.normalize();
  31944. uvs.push(ulength / bounds.width, 0);
  31945. uvs.push(ulength / bounds.width, 1);
  31946. ulength += v3.length();
  31947. uvs.push((ulength / bounds.width), 0);
  31948. uvs.push((ulength / bounds.width), 1);
  31949. if (!flip) {
  31950. normals.push(-vn.x, -vn.y, -vn.z);
  31951. normals.push(-vn.x, -vn.y, -vn.z);
  31952. normals.push(-vn.x, -vn.y, -vn.z);
  31953. normals.push(-vn.x, -vn.y, -vn.z);
  31954. indices.push(StartIndex);
  31955. indices.push(StartIndex + 1);
  31956. indices.push(StartIndex + 2);
  31957. indices.push(StartIndex + 1);
  31958. indices.push(StartIndex + 3);
  31959. indices.push(StartIndex + 2);
  31960. }
  31961. else {
  31962. normals.push(vn.x, vn.y, vn.z);
  31963. normals.push(vn.x, vn.y, vn.z);
  31964. normals.push(vn.x, vn.y, vn.z);
  31965. normals.push(vn.x, vn.y, vn.z);
  31966. indices.push(StartIndex);
  31967. indices.push(StartIndex + 2);
  31968. indices.push(StartIndex + 1);
  31969. indices.push(StartIndex + 1);
  31970. indices.push(StartIndex + 2);
  31971. indices.push(StartIndex + 3);
  31972. }
  31973. StartIndex += 4;
  31974. }
  31975. ;
  31976. };
  31977. return PolygonMeshBuilder;
  31978. })();
  31979. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31980. })(BABYLON || (BABYLON = {}));
  31981. var BABYLON;
  31982. (function (BABYLON) {
  31983. var Octree = (function () {
  31984. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  31985. if (maxDepth === void 0) { maxDepth = 2; }
  31986. this.maxDepth = maxDepth;
  31987. this.dynamicContent = new Array();
  31988. this._maxBlockCapacity = maxBlockCapacity || 64;
  31989. this._selectionContent = new BABYLON.SmartArray(1024);
  31990. this._creationFunc = creationFunc;
  31991. }
  31992. // Methods
  31993. Octree.prototype.update = function (worldMin, worldMax, entries) {
  31994. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  31995. };
  31996. Octree.prototype.addMesh = function (entry) {
  31997. for (var index = 0; index < this.blocks.length; index++) {
  31998. var block = this.blocks[index];
  31999. block.addEntry(entry);
  32000. }
  32001. };
  32002. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32003. this._selectionContent.reset();
  32004. for (var index = 0; index < this.blocks.length; index++) {
  32005. var block = this.blocks[index];
  32006. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32007. }
  32008. if (allowDuplicate) {
  32009. this._selectionContent.concat(this.dynamicContent);
  32010. }
  32011. else {
  32012. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32013. }
  32014. return this._selectionContent;
  32015. };
  32016. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32017. this._selectionContent.reset();
  32018. for (var index = 0; index < this.blocks.length; index++) {
  32019. var block = this.blocks[index];
  32020. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32021. }
  32022. if (allowDuplicate) {
  32023. this._selectionContent.concat(this.dynamicContent);
  32024. }
  32025. else {
  32026. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32027. }
  32028. return this._selectionContent;
  32029. };
  32030. Octree.prototype.intersectsRay = function (ray) {
  32031. this._selectionContent.reset();
  32032. for (var index = 0; index < this.blocks.length; index++) {
  32033. var block = this.blocks[index];
  32034. block.intersectsRay(ray, this._selectionContent);
  32035. }
  32036. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32037. return this._selectionContent;
  32038. };
  32039. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32040. target.blocks = new Array();
  32041. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32042. // Segmenting space
  32043. for (var x = 0; x < 2; x++) {
  32044. for (var y = 0; y < 2; y++) {
  32045. for (var z = 0; z < 2; z++) {
  32046. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32047. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32048. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32049. block.addEntries(entries);
  32050. target.blocks.push(block);
  32051. }
  32052. }
  32053. }
  32054. };
  32055. Octree.CreationFuncForMeshes = function (entry, block) {
  32056. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32057. block.entries.push(entry);
  32058. }
  32059. };
  32060. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32061. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32062. block.entries.push(entry);
  32063. }
  32064. };
  32065. return Octree;
  32066. })();
  32067. BABYLON.Octree = Octree;
  32068. })(BABYLON || (BABYLON = {}));
  32069. var BABYLON;
  32070. (function (BABYLON) {
  32071. var OctreeBlock = (function () {
  32072. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32073. this.entries = new Array();
  32074. this._boundingVectors = new Array();
  32075. this._capacity = capacity;
  32076. this._depth = depth;
  32077. this._maxDepth = maxDepth;
  32078. this._creationFunc = creationFunc;
  32079. this._minPoint = minPoint;
  32080. this._maxPoint = maxPoint;
  32081. this._boundingVectors.push(minPoint.clone());
  32082. this._boundingVectors.push(maxPoint.clone());
  32083. this._boundingVectors.push(minPoint.clone());
  32084. this._boundingVectors[2].x = maxPoint.x;
  32085. this._boundingVectors.push(minPoint.clone());
  32086. this._boundingVectors[3].y = maxPoint.y;
  32087. this._boundingVectors.push(minPoint.clone());
  32088. this._boundingVectors[4].z = maxPoint.z;
  32089. this._boundingVectors.push(maxPoint.clone());
  32090. this._boundingVectors[5].z = minPoint.z;
  32091. this._boundingVectors.push(maxPoint.clone());
  32092. this._boundingVectors[6].x = minPoint.x;
  32093. this._boundingVectors.push(maxPoint.clone());
  32094. this._boundingVectors[7].y = minPoint.y;
  32095. }
  32096. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32097. // Property
  32098. get: function () {
  32099. return this._capacity;
  32100. },
  32101. enumerable: true,
  32102. configurable: true
  32103. });
  32104. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32105. get: function () {
  32106. return this._minPoint;
  32107. },
  32108. enumerable: true,
  32109. configurable: true
  32110. });
  32111. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32112. get: function () {
  32113. return this._maxPoint;
  32114. },
  32115. enumerable: true,
  32116. configurable: true
  32117. });
  32118. // Methods
  32119. OctreeBlock.prototype.addEntry = function (entry) {
  32120. if (this.blocks) {
  32121. for (var index = 0; index < this.blocks.length; index++) {
  32122. var block = this.blocks[index];
  32123. block.addEntry(entry);
  32124. }
  32125. return;
  32126. }
  32127. this._creationFunc(entry, this);
  32128. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32129. this.createInnerBlocks();
  32130. }
  32131. };
  32132. OctreeBlock.prototype.addEntries = function (entries) {
  32133. for (var index = 0; index < entries.length; index++) {
  32134. var mesh = entries[index];
  32135. this.addEntry(mesh);
  32136. }
  32137. };
  32138. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32139. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32140. if (this.blocks) {
  32141. for (var index = 0; index < this.blocks.length; index++) {
  32142. var block = this.blocks[index];
  32143. block.select(frustumPlanes, selection, allowDuplicate);
  32144. }
  32145. return;
  32146. }
  32147. if (allowDuplicate) {
  32148. selection.concat(this.entries);
  32149. }
  32150. else {
  32151. selection.concatWithNoDuplicate(this.entries);
  32152. }
  32153. }
  32154. };
  32155. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32156. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32157. if (this.blocks) {
  32158. for (var index = 0; index < this.blocks.length; index++) {
  32159. var block = this.blocks[index];
  32160. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32161. }
  32162. return;
  32163. }
  32164. if (allowDuplicate) {
  32165. selection.concat(this.entries);
  32166. }
  32167. else {
  32168. selection.concatWithNoDuplicate(this.entries);
  32169. }
  32170. }
  32171. };
  32172. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32173. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32174. if (this.blocks) {
  32175. for (var index = 0; index < this.blocks.length; index++) {
  32176. var block = this.blocks[index];
  32177. block.intersectsRay(ray, selection);
  32178. }
  32179. return;
  32180. }
  32181. selection.concatWithNoDuplicate(this.entries);
  32182. }
  32183. };
  32184. OctreeBlock.prototype.createInnerBlocks = function () {
  32185. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32186. };
  32187. return OctreeBlock;
  32188. })();
  32189. BABYLON.OctreeBlock = OctreeBlock;
  32190. })(BABYLON || (BABYLON = {}));
  32191. var BABYLON;
  32192. (function (BABYLON) {
  32193. var BlurPostProcess = (function (_super) {
  32194. __extends(BlurPostProcess, _super);
  32195. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32196. var _this = this;
  32197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32198. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32199. this.direction = direction;
  32200. this.blurWidth = blurWidth;
  32201. this.onApply = function (effect) {
  32202. effect.setFloat2("screenSize", _this.width, _this.height);
  32203. effect.setVector2("direction", _this.direction);
  32204. effect.setFloat("blurWidth", _this.blurWidth);
  32205. };
  32206. }
  32207. return BlurPostProcess;
  32208. })(BABYLON.PostProcess);
  32209. BABYLON.BlurPostProcess = BlurPostProcess;
  32210. })(BABYLON || (BABYLON = {}));
  32211. var BABYLON;
  32212. (function (BABYLON) {
  32213. var RefractionPostProcess = (function (_super) {
  32214. __extends(RefractionPostProcess, _super);
  32215. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32216. var _this = this;
  32217. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32218. this.color = color;
  32219. this.depth = depth;
  32220. this.colorLevel = colorLevel;
  32221. this.onActivate = function (cam) {
  32222. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32223. };
  32224. this.onApply = function (effect) {
  32225. effect.setColor3("baseColor", _this.color);
  32226. effect.setFloat("depth", _this.depth);
  32227. effect.setFloat("colorLevel", _this.colorLevel);
  32228. effect.setTexture("refractionSampler", _this._refRexture);
  32229. };
  32230. }
  32231. // Methods
  32232. RefractionPostProcess.prototype.dispose = function (camera) {
  32233. if (this._refRexture) {
  32234. this._refRexture.dispose();
  32235. }
  32236. _super.prototype.dispose.call(this, camera);
  32237. };
  32238. return RefractionPostProcess;
  32239. })(BABYLON.PostProcess);
  32240. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32241. })(BABYLON || (BABYLON = {}));
  32242. var BABYLON;
  32243. (function (BABYLON) {
  32244. var BlackAndWhitePostProcess = (function (_super) {
  32245. __extends(BlackAndWhitePostProcess, _super);
  32246. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32247. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32248. }
  32249. return BlackAndWhitePostProcess;
  32250. })(BABYLON.PostProcess);
  32251. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32252. })(BABYLON || (BABYLON = {}));
  32253. var BABYLON;
  32254. (function (BABYLON) {
  32255. var ConvolutionPostProcess = (function (_super) {
  32256. __extends(ConvolutionPostProcess, _super);
  32257. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32258. var _this = this;
  32259. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32260. this.kernel = kernel;
  32261. this.onApply = function (effect) {
  32262. effect.setFloat2("screenSize", _this.width, _this.height);
  32263. effect.setArray("kernel", _this.kernel);
  32264. };
  32265. }
  32266. // Statics
  32267. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32268. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32269. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32270. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32271. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32272. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32273. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32274. return ConvolutionPostProcess;
  32275. })(BABYLON.PostProcess);
  32276. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32277. })(BABYLON || (BABYLON = {}));
  32278. var BABYLON;
  32279. (function (BABYLON) {
  32280. var FilterPostProcess = (function (_super) {
  32281. __extends(FilterPostProcess, _super);
  32282. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32283. var _this = this;
  32284. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32285. this.kernelMatrix = kernelMatrix;
  32286. this.onApply = function (effect) {
  32287. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32288. };
  32289. }
  32290. return FilterPostProcess;
  32291. })(BABYLON.PostProcess);
  32292. BABYLON.FilterPostProcess = FilterPostProcess;
  32293. })(BABYLON || (BABYLON = {}));
  32294. var BABYLON;
  32295. (function (BABYLON) {
  32296. var FxaaPostProcess = (function (_super) {
  32297. __extends(FxaaPostProcess, _super);
  32298. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32299. var _this = this;
  32300. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32301. this.onSizeChanged = function () {
  32302. _this.texelWidth = 1.0 / _this.width;
  32303. _this.texelHeight = 1.0 / _this.height;
  32304. };
  32305. this.onApply = function (effect) {
  32306. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32307. };
  32308. }
  32309. return FxaaPostProcess;
  32310. })(BABYLON.PostProcess);
  32311. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32312. })(BABYLON || (BABYLON = {}));
  32313. var BABYLON;
  32314. (function (BABYLON) {
  32315. var StereoscopicInterlacePostProcess = (function (_super) {
  32316. __extends(StereoscopicInterlacePostProcess, _super);
  32317. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32318. var _this = this;
  32319. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32320. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32321. this.onSizeChanged = function () {
  32322. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32323. };
  32324. this.onApply = function (effect) {
  32325. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32326. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32327. };
  32328. }
  32329. return StereoscopicInterlacePostProcess;
  32330. })(BABYLON.PostProcess);
  32331. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32332. })(BABYLON || (BABYLON = {}));
  32333. var BABYLON;
  32334. (function (BABYLON) {
  32335. var LensFlare = (function () {
  32336. function LensFlare(size, position, color, imgUrl, system) {
  32337. this.size = size;
  32338. this.position = position;
  32339. this.dispose = function () {
  32340. if (this.texture) {
  32341. this.texture.dispose();
  32342. }
  32343. // Remove from scene
  32344. var index = this._system.lensFlares.indexOf(this);
  32345. this._system.lensFlares.splice(index, 1);
  32346. };
  32347. this.color = color || new BABYLON.Color3(1, 1, 1);
  32348. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32349. this._system = system;
  32350. system.lensFlares.push(this);
  32351. }
  32352. return LensFlare;
  32353. })();
  32354. BABYLON.LensFlare = LensFlare;
  32355. })(BABYLON || (BABYLON = {}));
  32356. var BABYLON;
  32357. (function (BABYLON) {
  32358. var LensFlareSystem = (function () {
  32359. function LensFlareSystem(name, emitter, scene) {
  32360. this.name = name;
  32361. this.lensFlares = new Array();
  32362. this.borderLimit = 300;
  32363. this.layerMask = 0x0FFFFFFF;
  32364. this._vertexDeclaration = [2];
  32365. this._vertexStrideSize = 2 * 4;
  32366. this._isEnabled = true;
  32367. this._scene = scene;
  32368. this._emitter = emitter;
  32369. scene.lensFlareSystems.push(this);
  32370. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32371. // VBO
  32372. var vertices = [];
  32373. vertices.push(1, 1);
  32374. vertices.push(-1, 1);
  32375. vertices.push(-1, -1);
  32376. vertices.push(1, -1);
  32377. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32378. // Indices
  32379. var indices = [];
  32380. indices.push(0);
  32381. indices.push(1);
  32382. indices.push(2);
  32383. indices.push(0);
  32384. indices.push(2);
  32385. indices.push(3);
  32386. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32387. // Effects
  32388. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32389. }
  32390. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32391. get: function () {
  32392. return this._isEnabled;
  32393. },
  32394. set: function (value) {
  32395. this._isEnabled = value;
  32396. },
  32397. enumerable: true,
  32398. configurable: true
  32399. });
  32400. LensFlareSystem.prototype.getScene = function () {
  32401. return this._scene;
  32402. };
  32403. LensFlareSystem.prototype.getEmitter = function () {
  32404. return this._emitter;
  32405. };
  32406. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32407. this._emitter = newEmitter;
  32408. };
  32409. LensFlareSystem.prototype.getEmitterPosition = function () {
  32410. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32411. };
  32412. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32413. var position = this.getEmitterPosition();
  32414. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32415. this._positionX = position.x;
  32416. this._positionY = position.y;
  32417. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32418. if (position.z > 0) {
  32419. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32420. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32421. return true;
  32422. }
  32423. }
  32424. return false;
  32425. };
  32426. LensFlareSystem.prototype._isVisible = function () {
  32427. if (!this._isEnabled) {
  32428. return false;
  32429. }
  32430. var emitterPosition = this.getEmitterPosition();
  32431. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32432. var distance = direction.length();
  32433. direction.normalize();
  32434. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32435. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32436. return !pickInfo.hit || pickInfo.distance > distance;
  32437. };
  32438. LensFlareSystem.prototype.render = function () {
  32439. if (!this._effect.isReady())
  32440. return false;
  32441. var engine = this._scene.getEngine();
  32442. var viewport = this._scene.activeCamera.viewport;
  32443. var globalViewport = viewport.toGlobal(engine);
  32444. // Position
  32445. if (!this.computeEffectivePosition(globalViewport)) {
  32446. return false;
  32447. }
  32448. // Visibility
  32449. if (!this._isVisible()) {
  32450. return false;
  32451. }
  32452. // Intensity
  32453. var awayX;
  32454. var awayY;
  32455. if (this._positionX < this.borderLimit + globalViewport.x) {
  32456. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32457. }
  32458. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32459. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32460. }
  32461. else {
  32462. awayX = 0;
  32463. }
  32464. if (this._positionY < this.borderLimit + globalViewport.y) {
  32465. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32466. }
  32467. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32468. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32469. }
  32470. else {
  32471. awayY = 0;
  32472. }
  32473. var away = (awayX > awayY) ? awayX : awayY;
  32474. if (away > this.borderLimit) {
  32475. away = this.borderLimit;
  32476. }
  32477. var intensity = 1.0 - (away / this.borderLimit);
  32478. if (intensity < 0) {
  32479. return false;
  32480. }
  32481. if (intensity > 1.0) {
  32482. intensity = 1.0;
  32483. }
  32484. // Position
  32485. var centerX = globalViewport.x + globalViewport.width / 2;
  32486. var centerY = globalViewport.y + globalViewport.height / 2;
  32487. var distX = centerX - this._positionX;
  32488. var distY = centerY - this._positionY;
  32489. // Effects
  32490. engine.enableEffect(this._effect);
  32491. engine.setState(false);
  32492. engine.setDepthBuffer(false);
  32493. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32494. // VBOs
  32495. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32496. // Flares
  32497. for (var index = 0; index < this.lensFlares.length; index++) {
  32498. var flare = this.lensFlares[index];
  32499. var x = centerX - (distX * flare.position);
  32500. var y = centerY - (distY * flare.position);
  32501. var cw = flare.size;
  32502. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32503. var cx = 2 * (x / globalViewport.width) - 1.0;
  32504. var cy = 1.0 - 2 * (y / globalViewport.height);
  32505. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32506. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32507. // Texture
  32508. this._effect.setTexture("textureSampler", flare.texture);
  32509. // Color
  32510. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32511. // Draw order
  32512. engine.draw(true, 0, 6);
  32513. }
  32514. engine.setDepthBuffer(true);
  32515. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32516. return true;
  32517. };
  32518. LensFlareSystem.prototype.dispose = function () {
  32519. if (this._vertexBuffer) {
  32520. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32521. this._vertexBuffer = null;
  32522. }
  32523. if (this._indexBuffer) {
  32524. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32525. this._indexBuffer = null;
  32526. }
  32527. while (this.lensFlares.length) {
  32528. this.lensFlares[0].dispose();
  32529. }
  32530. // Remove from scene
  32531. var index = this._scene.lensFlareSystems.indexOf(this);
  32532. this._scene.lensFlareSystems.splice(index, 1);
  32533. };
  32534. return LensFlareSystem;
  32535. })();
  32536. BABYLON.LensFlareSystem = LensFlareSystem;
  32537. })(BABYLON || (BABYLON = {}));
  32538. var BABYLON;
  32539. (function (BABYLON) {
  32540. // We're mainly based on the logic defined into the FreeCamera code
  32541. var DeviceOrientationCamera = (function (_super) {
  32542. __extends(DeviceOrientationCamera, _super);
  32543. function DeviceOrientationCamera(name, position, scene) {
  32544. var _this = this;
  32545. _super.call(this, name, position, scene);
  32546. this._offsetX = null;
  32547. this._offsetY = null;
  32548. this._orientationGamma = 0;
  32549. this._orientationBeta = 0;
  32550. this._initialOrientationGamma = 0;
  32551. this._initialOrientationBeta = 0;
  32552. this.angularSensibility = 10000.0;
  32553. this.moveSensibility = 50.0;
  32554. window.addEventListener("resize", function () {
  32555. _this._initialOrientationGamma = null;
  32556. }, false);
  32557. }
  32558. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32559. var _this = this;
  32560. if (this._attachedCanvas) {
  32561. return;
  32562. }
  32563. this._attachedCanvas = canvas;
  32564. if (!this._orientationChanged) {
  32565. this._orientationChanged = function (evt) {
  32566. if (!_this._initialOrientationGamma) {
  32567. _this._initialOrientationGamma = evt.gamma;
  32568. _this._initialOrientationBeta = evt.beta;
  32569. }
  32570. _this._orientationGamma = evt.gamma;
  32571. _this._orientationBeta = evt.beta;
  32572. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32573. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32574. };
  32575. }
  32576. window.addEventListener("deviceorientation", this._orientationChanged);
  32577. };
  32578. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32579. if (this._attachedCanvas != canvas) {
  32580. return;
  32581. }
  32582. window.removeEventListener("deviceorientation", this._orientationChanged);
  32583. this._attachedCanvas = null;
  32584. this._orientationGamma = 0;
  32585. this._orientationBeta = 0;
  32586. this._initialOrientationGamma = 0;
  32587. this._initialOrientationBeta = 0;
  32588. };
  32589. DeviceOrientationCamera.prototype._checkInputs = function () {
  32590. if (!this._offsetX) {
  32591. return;
  32592. }
  32593. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32594. var speed = this._computeLocalCameraSpeed();
  32595. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32596. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32597. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32598. _super.prototype._checkInputs.call(this);
  32599. };
  32600. return DeviceOrientationCamera;
  32601. })(BABYLON.FreeCamera);
  32602. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32603. })(BABYLON || (BABYLON = {}));
  32604. var BABYLON;
  32605. (function (BABYLON) {
  32606. var Gamepads = (function () {
  32607. function Gamepads(ongamedpadconnected) {
  32608. var _this = this;
  32609. this.babylonGamepads = [];
  32610. this.oneGamepadConnected = false;
  32611. this.isMonitoring = false;
  32612. this.gamepadEventSupported = 'GamepadEvent' in window;
  32613. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32614. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32615. 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=";
  32616. this._callbackGamepadConnected = ongamedpadconnected;
  32617. if (this.gamepadSupportAvailable) {
  32618. // Checking if the gamepad connected event is supported (like in Firefox)
  32619. if (this.gamepadEventSupported) {
  32620. window.addEventListener('gamepadconnected', function (evt) {
  32621. _this._onGamepadConnected(evt);
  32622. }, false);
  32623. window.addEventListener('gamepaddisconnected', function (evt) {
  32624. _this._onGamepadDisconnected(evt);
  32625. }, false);
  32626. }
  32627. else {
  32628. this._startMonitoringGamepads();
  32629. }
  32630. if (!this.oneGamepadConnected) {
  32631. this._insertGamepadDOMInstructions();
  32632. }
  32633. }
  32634. else {
  32635. this._insertGamepadDOMNotSupported();
  32636. }
  32637. }
  32638. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32639. Gamepads.gamepadDOMInfo = document.createElement("div");
  32640. var buttonAImage = document.createElement("img");
  32641. buttonAImage.src = this.buttonADataURL;
  32642. var spanMessage = document.createElement("span");
  32643. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32644. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32645. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32646. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32647. Gamepads.gamepadDOMInfo.style.width = "100%";
  32648. Gamepads.gamepadDOMInfo.style.height = "48px";
  32649. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32650. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32651. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32652. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32653. buttonAImage.style.position = "relative";
  32654. buttonAImage.style.bottom = "8px";
  32655. spanMessage.style.position = "relative";
  32656. spanMessage.style.fontSize = "32px";
  32657. spanMessage.style.bottom = "32px";
  32658. spanMessage.style.color = "green";
  32659. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32660. };
  32661. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32662. Gamepads.gamepadDOMInfo = document.createElement("div");
  32663. var spanMessage = document.createElement("span");
  32664. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32665. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32666. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32667. Gamepads.gamepadDOMInfo.style.width = "100%";
  32668. Gamepads.gamepadDOMInfo.style.height = "40px";
  32669. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32670. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32671. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32672. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32673. spanMessage.style.position = "relative";
  32674. spanMessage.style.fontSize = "32px";
  32675. spanMessage.style.color = "red";
  32676. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32677. };
  32678. Gamepads.prototype.dispose = function () {
  32679. if (Gamepads.gamepadDOMInfo) {
  32680. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32681. }
  32682. };
  32683. Gamepads.prototype._onGamepadConnected = function (evt) {
  32684. var newGamepad = this._addNewGamepad(evt.gamepad);
  32685. if (this._callbackGamepadConnected)
  32686. this._callbackGamepadConnected(newGamepad);
  32687. this._startMonitoringGamepads();
  32688. };
  32689. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32690. if (!this.oneGamepadConnected) {
  32691. this.oneGamepadConnected = true;
  32692. if (Gamepads.gamepadDOMInfo) {
  32693. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32694. Gamepads.gamepadDOMInfo = null;
  32695. }
  32696. }
  32697. var newGamepad;
  32698. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32699. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32700. }
  32701. else {
  32702. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32703. }
  32704. this.babylonGamepads.push(newGamepad);
  32705. return newGamepad;
  32706. };
  32707. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32708. // Remove the gamepad from the list of gamepads to monitor.
  32709. for (var i in this.babylonGamepads) {
  32710. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32711. this.babylonGamepads.splice(i, 1);
  32712. break;
  32713. }
  32714. }
  32715. // If no gamepads are left, stop the polling loop.
  32716. if (this.babylonGamepads.length == 0) {
  32717. this._stopMonitoringGamepads();
  32718. }
  32719. };
  32720. Gamepads.prototype._startMonitoringGamepads = function () {
  32721. if (!this.isMonitoring) {
  32722. this.isMonitoring = true;
  32723. this._checkGamepadsStatus();
  32724. }
  32725. };
  32726. Gamepads.prototype._stopMonitoringGamepads = function () {
  32727. this.isMonitoring = false;
  32728. };
  32729. Gamepads.prototype._checkGamepadsStatus = function () {
  32730. var _this = this;
  32731. // updating gamepad objects
  32732. this._updateGamepadObjects();
  32733. for (var i in this.babylonGamepads) {
  32734. this.babylonGamepads[i].update();
  32735. }
  32736. if (this.isMonitoring) {
  32737. if (window.requestAnimationFrame) {
  32738. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32739. }
  32740. else if (window.mozRequestAnimationFrame) {
  32741. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32742. }
  32743. else if (window.webkitRequestAnimationFrame) {
  32744. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32745. }
  32746. }
  32747. };
  32748. // This function is called only on Chrome, which does not yet support
  32749. // connection/disconnection events, but requires you to monitor
  32750. // an array for changes.
  32751. Gamepads.prototype._updateGamepadObjects = function () {
  32752. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32753. for (var i = 0; i < gamepads.length; i++) {
  32754. if (gamepads[i]) {
  32755. if (!(gamepads[i].index in this.babylonGamepads)) {
  32756. var newGamepad = this._addNewGamepad(gamepads[i]);
  32757. if (this._callbackGamepadConnected) {
  32758. this._callbackGamepadConnected(newGamepad);
  32759. }
  32760. }
  32761. else {
  32762. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32763. }
  32764. }
  32765. }
  32766. };
  32767. return Gamepads;
  32768. })();
  32769. BABYLON.Gamepads = Gamepads;
  32770. var StickValues = (function () {
  32771. function StickValues(x, y) {
  32772. this.x = x;
  32773. this.y = y;
  32774. }
  32775. return StickValues;
  32776. })();
  32777. BABYLON.StickValues = StickValues;
  32778. var Gamepad = (function () {
  32779. function Gamepad(id, index, browserGamepad) {
  32780. this.id = id;
  32781. this.index = index;
  32782. this.browserGamepad = browserGamepad;
  32783. if (this.browserGamepad.axes.length >= 2) {
  32784. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32785. }
  32786. if (this.browserGamepad.axes.length >= 4) {
  32787. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32788. }
  32789. }
  32790. Gamepad.prototype.onleftstickchanged = function (callback) {
  32791. this._onleftstickchanged = callback;
  32792. };
  32793. Gamepad.prototype.onrightstickchanged = function (callback) {
  32794. this._onrightstickchanged = callback;
  32795. };
  32796. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32797. get: function () {
  32798. return this._leftStick;
  32799. },
  32800. set: function (newValues) {
  32801. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32802. this._onleftstickchanged(newValues);
  32803. }
  32804. this._leftStick = newValues;
  32805. },
  32806. enumerable: true,
  32807. configurable: true
  32808. });
  32809. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32810. get: function () {
  32811. return this._rightStick;
  32812. },
  32813. set: function (newValues) {
  32814. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32815. this._onrightstickchanged(newValues);
  32816. }
  32817. this._rightStick = newValues;
  32818. },
  32819. enumerable: true,
  32820. configurable: true
  32821. });
  32822. Gamepad.prototype.update = function () {
  32823. if (this._leftStick) {
  32824. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32825. }
  32826. if (this._rightStick) {
  32827. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32828. }
  32829. };
  32830. return Gamepad;
  32831. })();
  32832. BABYLON.Gamepad = Gamepad;
  32833. var GenericPad = (function (_super) {
  32834. __extends(GenericPad, _super);
  32835. function GenericPad(id, index, gamepad) {
  32836. _super.call(this, id, index, gamepad);
  32837. this.id = id;
  32838. this.index = index;
  32839. this.gamepad = gamepad;
  32840. this._buttons = new Array(gamepad.buttons.length);
  32841. }
  32842. GenericPad.prototype.onbuttondown = function (callback) {
  32843. this._onbuttondown = callback;
  32844. };
  32845. GenericPad.prototype.onbuttonup = function (callback) {
  32846. this._onbuttonup = callback;
  32847. };
  32848. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32849. if (newValue !== currentValue) {
  32850. if (this._onbuttondown && newValue === 1) {
  32851. this._onbuttondown(buttonIndex);
  32852. }
  32853. if (this._onbuttonup && newValue === 0) {
  32854. this._onbuttonup(buttonIndex);
  32855. }
  32856. }
  32857. return newValue;
  32858. };
  32859. GenericPad.prototype.update = function () {
  32860. _super.prototype.update.call(this);
  32861. for (var index = 0; index < this._buttons.length; index++) {
  32862. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32863. }
  32864. };
  32865. return GenericPad;
  32866. })(Gamepad);
  32867. BABYLON.GenericPad = GenericPad;
  32868. (function (Xbox360Button) {
  32869. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32870. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32871. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32872. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32873. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32874. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32875. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32876. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32877. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32878. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32879. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32880. var Xbox360Button = BABYLON.Xbox360Button;
  32881. (function (Xbox360Dpad) {
  32882. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  32883. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  32884. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  32885. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  32886. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  32887. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  32888. var Xbox360Pad = (function (_super) {
  32889. __extends(Xbox360Pad, _super);
  32890. function Xbox360Pad() {
  32891. _super.apply(this, arguments);
  32892. this._leftTrigger = 0;
  32893. this._rightTrigger = 0;
  32894. this._buttonA = 0;
  32895. this._buttonB = 0;
  32896. this._buttonX = 0;
  32897. this._buttonY = 0;
  32898. this._buttonBack = 0;
  32899. this._buttonStart = 0;
  32900. this._buttonLB = 0;
  32901. this._buttonRB = 0;
  32902. this._buttonLeftStick = 0;
  32903. this._buttonRightStick = 0;
  32904. this._dPadUp = 0;
  32905. this._dPadDown = 0;
  32906. this._dPadLeft = 0;
  32907. this._dPadRight = 0;
  32908. }
  32909. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  32910. this._onlefttriggerchanged = callback;
  32911. };
  32912. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  32913. this._onrighttriggerchanged = callback;
  32914. };
  32915. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  32916. get: function () {
  32917. return this._leftTrigger;
  32918. },
  32919. set: function (newValue) {
  32920. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  32921. this._onlefttriggerchanged(newValue);
  32922. }
  32923. this._leftTrigger = newValue;
  32924. },
  32925. enumerable: true,
  32926. configurable: true
  32927. });
  32928. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  32929. get: function () {
  32930. return this._rightTrigger;
  32931. },
  32932. set: function (newValue) {
  32933. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  32934. this._onrighttriggerchanged(newValue);
  32935. }
  32936. this._rightTrigger = newValue;
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. Xbox360Pad.prototype.onbuttondown = function (callback) {
  32942. this._onbuttondown = callback;
  32943. };
  32944. Xbox360Pad.prototype.onbuttonup = function (callback) {
  32945. this._onbuttonup = callback;
  32946. };
  32947. Xbox360Pad.prototype.ondpaddown = function (callback) {
  32948. this._ondpaddown = callback;
  32949. };
  32950. Xbox360Pad.prototype.ondpadup = function (callback) {
  32951. this._ondpadup = callback;
  32952. };
  32953. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  32954. if (newValue !== currentValue) {
  32955. if (this._onbuttondown && newValue === 1) {
  32956. this._onbuttondown(buttonType);
  32957. }
  32958. if (this._onbuttonup && newValue === 0) {
  32959. this._onbuttonup(buttonType);
  32960. }
  32961. }
  32962. return newValue;
  32963. };
  32964. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  32965. if (newValue !== currentValue) {
  32966. if (this._ondpaddown && newValue === 1) {
  32967. this._ondpaddown(buttonType);
  32968. }
  32969. if (this._ondpadup && newValue === 0) {
  32970. this._ondpadup(buttonType);
  32971. }
  32972. }
  32973. return newValue;
  32974. };
  32975. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  32976. get: function () {
  32977. return this._buttonA;
  32978. },
  32979. set: function (value) {
  32980. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  32986. get: function () {
  32987. return this._buttonB;
  32988. },
  32989. set: function (value) {
  32990. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  32991. },
  32992. enumerable: true,
  32993. configurable: true
  32994. });
  32995. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  32996. get: function () {
  32997. return this._buttonX;
  32998. },
  32999. set: function (value) {
  33000. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33001. },
  33002. enumerable: true,
  33003. configurable: true
  33004. });
  33005. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33006. get: function () {
  33007. return this._buttonY;
  33008. },
  33009. set: function (value) {
  33010. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33011. },
  33012. enumerable: true,
  33013. configurable: true
  33014. });
  33015. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33016. get: function () {
  33017. return this._buttonStart;
  33018. },
  33019. set: function (value) {
  33020. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33021. },
  33022. enumerable: true,
  33023. configurable: true
  33024. });
  33025. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33026. get: function () {
  33027. return this._buttonBack;
  33028. },
  33029. set: function (value) {
  33030. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33031. },
  33032. enumerable: true,
  33033. configurable: true
  33034. });
  33035. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33036. get: function () {
  33037. return this._buttonLB;
  33038. },
  33039. set: function (value) {
  33040. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33041. },
  33042. enumerable: true,
  33043. configurable: true
  33044. });
  33045. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33046. get: function () {
  33047. return this._buttonRB;
  33048. },
  33049. set: function (value) {
  33050. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33051. },
  33052. enumerable: true,
  33053. configurable: true
  33054. });
  33055. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33056. get: function () {
  33057. return this._buttonLeftStick;
  33058. },
  33059. set: function (value) {
  33060. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33061. },
  33062. enumerable: true,
  33063. configurable: true
  33064. });
  33065. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33066. get: function () {
  33067. return this._buttonRightStick;
  33068. },
  33069. set: function (value) {
  33070. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33076. get: function () {
  33077. return this._dPadUp;
  33078. },
  33079. set: function (value) {
  33080. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33081. },
  33082. enumerable: true,
  33083. configurable: true
  33084. });
  33085. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33086. get: function () {
  33087. return this._dPadDown;
  33088. },
  33089. set: function (value) {
  33090. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33091. },
  33092. enumerable: true,
  33093. configurable: true
  33094. });
  33095. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33096. get: function () {
  33097. return this._dPadLeft;
  33098. },
  33099. set: function (value) {
  33100. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33101. },
  33102. enumerable: true,
  33103. configurable: true
  33104. });
  33105. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33106. get: function () {
  33107. return this._dPadRight;
  33108. },
  33109. set: function (value) {
  33110. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. Xbox360Pad.prototype.update = function () {
  33116. _super.prototype.update.call(this);
  33117. this.buttonA = this.browserGamepad.buttons[0].value;
  33118. this.buttonB = this.browserGamepad.buttons[1].value;
  33119. this.buttonX = this.browserGamepad.buttons[2].value;
  33120. this.buttonY = this.browserGamepad.buttons[3].value;
  33121. this.buttonLB = this.browserGamepad.buttons[4].value;
  33122. this.buttonRB = this.browserGamepad.buttons[5].value;
  33123. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33124. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33125. this.buttonBack = this.browserGamepad.buttons[8].value;
  33126. this.buttonStart = this.browserGamepad.buttons[9].value;
  33127. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33128. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33129. this.dPadUp = this.browserGamepad.buttons[12].value;
  33130. this.dPadDown = this.browserGamepad.buttons[13].value;
  33131. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33132. this.dPadRight = this.browserGamepad.buttons[15].value;
  33133. };
  33134. return Xbox360Pad;
  33135. })(Gamepad);
  33136. BABYLON.Xbox360Pad = Xbox360Pad;
  33137. })(BABYLON || (BABYLON = {}));
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. // We're mainly based on the logic defined into the FreeCamera code
  33141. var GamepadCamera = (function (_super) {
  33142. __extends(GamepadCamera, _super);
  33143. function GamepadCamera(name, position, scene) {
  33144. var _this = this;
  33145. _super.call(this, name, position, scene);
  33146. this.angularSensibility = 200;
  33147. this.moveSensibility = 75;
  33148. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33149. }
  33150. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33151. // Only the first gamepad can control the camera
  33152. if (gamepad.index === 0) {
  33153. this._gamepad = gamepad;
  33154. }
  33155. };
  33156. GamepadCamera.prototype._checkInputs = function () {
  33157. if (this._gamepad) {
  33158. var LSValues = this._gamepad.leftStick;
  33159. var normalizedLX = LSValues.x / this.moveSensibility;
  33160. var normalizedLY = LSValues.y / this.moveSensibility;
  33161. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33162. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33163. var RSValues = this._gamepad.rightStick;
  33164. var normalizedRX = RSValues.x / this.angularSensibility;
  33165. var normalizedRY = RSValues.y / this.angularSensibility;
  33166. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33167. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33168. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33169. var speed = this._computeLocalCameraSpeed() * 50.0;
  33170. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33171. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33172. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33173. }
  33174. _super.prototype._checkInputs.call(this);
  33175. };
  33176. GamepadCamera.prototype.dispose = function () {
  33177. this._gamepads.dispose();
  33178. _super.prototype.dispose.call(this);
  33179. };
  33180. return GamepadCamera;
  33181. })(BABYLON.FreeCamera);
  33182. BABYLON.GamepadCamera = GamepadCamera;
  33183. })(BABYLON || (BABYLON = {}));
  33184. var BABYLON;
  33185. (function (BABYLON) {
  33186. var Analyser = (function () {
  33187. function Analyser(scene) {
  33188. this.SMOOTHING = 0.75;
  33189. this.FFT_SIZE = 512;
  33190. this.BARGRAPHAMPLITUDE = 256;
  33191. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33192. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33193. this._scene = scene;
  33194. this._audioEngine = BABYLON.Engine.audioEngine;
  33195. if (this._audioEngine.canUseWebAudio) {
  33196. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33197. this._webAudioAnalyser.minDecibels = -140;
  33198. this._webAudioAnalyser.maxDecibels = 0;
  33199. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33200. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33201. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33202. }
  33203. }
  33204. Analyser.prototype.getFrequencyBinCount = function () {
  33205. if (this._audioEngine.canUseWebAudio) {
  33206. return this._webAudioAnalyser.frequencyBinCount;
  33207. }
  33208. else {
  33209. return 0;
  33210. }
  33211. };
  33212. Analyser.prototype.getByteFrequencyData = function () {
  33213. if (this._audioEngine.canUseWebAudio) {
  33214. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33215. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33216. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33217. }
  33218. return this._byteFreqs;
  33219. };
  33220. Analyser.prototype.getByteTimeDomainData = function () {
  33221. if (this._audioEngine.canUseWebAudio) {
  33222. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33223. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33224. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33225. }
  33226. return this._byteTime;
  33227. };
  33228. Analyser.prototype.getFloatFrequencyData = function () {
  33229. if (this._audioEngine.canUseWebAudio) {
  33230. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33231. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33232. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33233. }
  33234. return this._floatFreqs;
  33235. };
  33236. Analyser.prototype.drawDebugCanvas = function () {
  33237. var _this = this;
  33238. if (this._audioEngine.canUseWebAudio) {
  33239. if (!this._debugCanvas) {
  33240. this._debugCanvas = document.createElement("canvas");
  33241. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33242. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33243. this._debugCanvas.style.position = "absolute";
  33244. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33245. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33246. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33247. document.body.appendChild(this._debugCanvas);
  33248. this._registerFunc = function () {
  33249. _this.drawDebugCanvas();
  33250. };
  33251. this._scene.registerBeforeRender(this._registerFunc);
  33252. }
  33253. if (this._registerFunc) {
  33254. var workingArray = this.getByteFrequencyData();
  33255. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33256. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33257. // Draw the frequency domain chart.
  33258. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33259. var value = workingArray[i];
  33260. var percent = value / this.BARGRAPHAMPLITUDE;
  33261. var height = this.DEBUGCANVASSIZE.height * percent;
  33262. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33263. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33264. var hue = i / this.getFrequencyBinCount() * 360;
  33265. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33266. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33267. }
  33268. }
  33269. }
  33270. };
  33271. Analyser.prototype.stopDebugCanvas = function () {
  33272. if (this._debugCanvas) {
  33273. this._scene.unregisterBeforeRender(this._registerFunc);
  33274. this._registerFunc = null;
  33275. document.body.removeChild(this._debugCanvas);
  33276. this._debugCanvas = null;
  33277. this._debugCanvasContext = null;
  33278. }
  33279. };
  33280. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33281. if (this._audioEngine.canUseWebAudio) {
  33282. inputAudioNode.connect(this._webAudioAnalyser);
  33283. this._webAudioAnalyser.connect(outputAudioNode);
  33284. }
  33285. };
  33286. Analyser.prototype.dispose = function () {
  33287. if (this._audioEngine.canUseWebAudio) {
  33288. this._webAudioAnalyser.disconnect();
  33289. }
  33290. };
  33291. return Analyser;
  33292. })();
  33293. BABYLON.Analyser = Analyser;
  33294. })(BABYLON || (BABYLON = {}));
  33295. var BABYLON;
  33296. (function (BABYLON) {
  33297. var AudioEngine = (function () {
  33298. function AudioEngine() {
  33299. this._audioContext = null;
  33300. this._audioContextInitialized = false;
  33301. this.canUseWebAudio = false;
  33302. this.WarnedWebAudioUnsupported = false;
  33303. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33304. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33305. this.canUseWebAudio = true;
  33306. }
  33307. }
  33308. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33309. get: function () {
  33310. if (!this._audioContextInitialized) {
  33311. this._initializeAudioContext();
  33312. }
  33313. return this._audioContext;
  33314. },
  33315. enumerable: true,
  33316. configurable: true
  33317. });
  33318. AudioEngine.prototype._initializeAudioContext = function () {
  33319. try {
  33320. if (this.canUseWebAudio) {
  33321. this._audioContext = new AudioContext();
  33322. // create a global volume gain node
  33323. this.masterGain = this._audioContext.createGain();
  33324. this.masterGain.gain.value = 1;
  33325. this.masterGain.connect(this._audioContext.destination);
  33326. this._audioContextInitialized = true;
  33327. }
  33328. }
  33329. catch (e) {
  33330. this.canUseWebAudio = false;
  33331. BABYLON.Tools.Error("Web Audio: " + e.message);
  33332. }
  33333. };
  33334. AudioEngine.prototype.dispose = function () {
  33335. if (this.canUseWebAudio && this._audioContextInitialized) {
  33336. if (this._connectedAnalyser) {
  33337. this._connectedAnalyser.stopDebugCanvas();
  33338. this._connectedAnalyser.dispose();
  33339. this.masterGain.disconnect();
  33340. this.masterGain.connect(this._audioContext.destination);
  33341. this._connectedAnalyser = null;
  33342. }
  33343. this.masterGain.gain.value = 1;
  33344. }
  33345. this.WarnedWebAudioUnsupported = false;
  33346. };
  33347. AudioEngine.prototype.getGlobalVolume = function () {
  33348. if (this.canUseWebAudio && this._audioContextInitialized) {
  33349. return this.masterGain.gain.value;
  33350. }
  33351. else {
  33352. return -1;
  33353. }
  33354. };
  33355. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33356. if (this.canUseWebAudio && this._audioContextInitialized) {
  33357. this.masterGain.gain.value = newVolume;
  33358. }
  33359. };
  33360. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33361. if (this._connectedAnalyser) {
  33362. this._connectedAnalyser.stopDebugCanvas();
  33363. }
  33364. if (this.canUseWebAudio && this._audioContextInitialized) {
  33365. this._connectedAnalyser = analyser;
  33366. this.masterGain.disconnect();
  33367. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33368. }
  33369. };
  33370. return AudioEngine;
  33371. })();
  33372. BABYLON.AudioEngine = AudioEngine;
  33373. })(BABYLON || (BABYLON = {}));
  33374. var BABYLON;
  33375. (function (BABYLON) {
  33376. var Sound = (function () {
  33377. /**
  33378. * Create a sound and attach it to a scene
  33379. * @param name Name of your sound
  33380. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33381. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33382. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33383. */
  33384. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33385. var _this = this;
  33386. this.autoplay = false;
  33387. this.loop = false;
  33388. this.useCustomAttenuation = false;
  33389. this.spatialSound = false;
  33390. this.refDistance = 1;
  33391. this.rolloffFactor = 1;
  33392. this.maxDistance = 100;
  33393. this.distanceModel = "linear";
  33394. this._panningModel = "equalpower";
  33395. this._playbackRate = 1;
  33396. this._streaming = false;
  33397. this._startTime = 0;
  33398. this._startOffset = 0;
  33399. this._position = BABYLON.Vector3.Zero();
  33400. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33401. this._volume = 1;
  33402. this._isLoaded = false;
  33403. this._isReadyToPlay = false;
  33404. this.isPlaying = false;
  33405. this.isPaused = false;
  33406. this._isDirectional = false;
  33407. // Used if you'd like to create a directional sound.
  33408. // If not set, the sound will be omnidirectional
  33409. this._coneInnerAngle = 360;
  33410. this._coneOuterAngle = 360;
  33411. this._coneOuterGain = 0;
  33412. this._isOutputConnected = false;
  33413. this.name = name;
  33414. this._scene = scene;
  33415. this._readyToPlayCallback = readyToPlayCallback;
  33416. // Default custom attenuation function is a linear attenuation
  33417. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33418. if (currentDistance < maxDistance) {
  33419. return currentVolume * (1 - currentDistance / maxDistance);
  33420. }
  33421. else {
  33422. return 0;
  33423. }
  33424. };
  33425. if (options) {
  33426. this.autoplay = options.autoplay || false;
  33427. this.loop = options.loop || false;
  33428. // if volume === 0, we need another way to check this option
  33429. if (options.volume !== undefined) {
  33430. this._volume = options.volume;
  33431. }
  33432. this.spatialSound = options.spatialSound || false;
  33433. this.maxDistance = options.maxDistance || 100;
  33434. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33435. this.rolloffFactor = options.rolloffFactor || 1;
  33436. this.refDistance = options.refDistance || 1;
  33437. this.distanceModel = options.distanceModel || "linear";
  33438. this._playbackRate = options.playbackRate || 1;
  33439. this._streaming = options.streaming || false;
  33440. }
  33441. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33442. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33443. this._soundGain.gain.value = this._volume;
  33444. this._inputAudioNode = this._soundGain;
  33445. this._ouputAudioNode = this._soundGain;
  33446. if (this.spatialSound) {
  33447. this._createSpatialParameters();
  33448. }
  33449. this._scene.mainSoundTrack.AddSound(this);
  33450. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33451. if (urlOrArrayBuffer) {
  33452. // If it's an URL
  33453. if (typeof (urlOrArrayBuffer) === "string") {
  33454. // Loading sound using XHR2
  33455. if (!this._streaming) {
  33456. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33457. }
  33458. else {
  33459. this._htmlAudioElement = new Audio();
  33460. this._htmlAudioElement.src = urlOrArrayBuffer;
  33461. this._htmlAudioElement.controls = false;
  33462. this._htmlAudioElement.loop = this.loop;
  33463. this._isReadyToPlay = true;
  33464. document.body.appendChild(this._htmlAudioElement);
  33465. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33466. if (this._readyToPlayCallback) {
  33467. window.setTimeout(function () {
  33468. _this._readyToPlayCallback();
  33469. }, 1000);
  33470. }
  33471. if (this.autoplay) {
  33472. this.play();
  33473. }
  33474. }
  33475. }
  33476. else {
  33477. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33478. this._soundLoaded(urlOrArrayBuffer);
  33479. }
  33480. else {
  33481. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33482. }
  33483. }
  33484. }
  33485. }
  33486. else {
  33487. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33488. this._scene.mainSoundTrack.AddSound(this);
  33489. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33490. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33491. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33492. }
  33493. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33494. if (this._readyToPlayCallback) {
  33495. window.setTimeout(function () {
  33496. _this._readyToPlayCallback();
  33497. }, 1000);
  33498. }
  33499. }
  33500. }
  33501. Sound.prototype.dispose = function () {
  33502. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33503. if (this.isPlaying) {
  33504. this.stop();
  33505. }
  33506. this._isReadyToPlay = false;
  33507. if (this.soundTrackId === -1) {
  33508. this._scene.mainSoundTrack.RemoveSound(this);
  33509. }
  33510. else {
  33511. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33512. }
  33513. if (this._soundGain) {
  33514. this._soundGain.disconnect();
  33515. this._soundGain = null;
  33516. }
  33517. if (this._soundPanner) {
  33518. this._soundPanner.disconnect();
  33519. this._soundPanner = null;
  33520. }
  33521. if (this._soundSource) {
  33522. this._soundSource.disconnect();
  33523. this._soundSource = null;
  33524. }
  33525. this._audioBuffer = null;
  33526. if (this._htmlAudioElement) {
  33527. this._htmlAudioElement.pause();
  33528. this._htmlAudioElement.src = "";
  33529. document.body.removeChild(this._htmlAudioElement);
  33530. }
  33531. if (this._connectedMesh) {
  33532. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33533. this._connectedMesh = null;
  33534. }
  33535. }
  33536. };
  33537. Sound.prototype._soundLoaded = function (audioData) {
  33538. var _this = this;
  33539. this._isLoaded = true;
  33540. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33541. _this._audioBuffer = buffer;
  33542. _this._isReadyToPlay = true;
  33543. if (_this.autoplay) {
  33544. _this.play();
  33545. }
  33546. if (_this._readyToPlayCallback) {
  33547. _this._readyToPlayCallback();
  33548. }
  33549. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33550. };
  33551. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33552. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33553. this._audioBuffer = audioBuffer;
  33554. this._isReadyToPlay = true;
  33555. }
  33556. };
  33557. Sound.prototype.updateOptions = function (options) {
  33558. if (options) {
  33559. this.loop = options.loop || this.loop;
  33560. this.maxDistance = options.maxDistance || this.maxDistance;
  33561. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33562. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33563. this.refDistance = options.refDistance || this.refDistance;
  33564. this.distanceModel = options.distanceModel || this.distanceModel;
  33565. this._playbackRate = options.playbackRate || this._playbackRate;
  33566. this._updateSpatialParameters();
  33567. if (this.isPlaying) {
  33568. if (this._streaming) {
  33569. this._htmlAudioElement.playbackRate = this._playbackRate;
  33570. }
  33571. else {
  33572. this._soundSource.playbackRate.value = this._playbackRate;
  33573. }
  33574. }
  33575. }
  33576. };
  33577. Sound.prototype._createSpatialParameters = function () {
  33578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33579. if (this._scene.headphone) {
  33580. this._panningModel = "HRTF";
  33581. }
  33582. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33583. this._updateSpatialParameters();
  33584. this._soundPanner.connect(this._ouputAudioNode);
  33585. this._inputAudioNode = this._soundPanner;
  33586. }
  33587. };
  33588. Sound.prototype._updateSpatialParameters = function () {
  33589. if (this.spatialSound) {
  33590. if (this.useCustomAttenuation) {
  33591. // Tricks to disable in a way embedded Web Audio attenuation
  33592. this._soundPanner.distanceModel = "linear";
  33593. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33594. this._soundPanner.refDistance = 1;
  33595. this._soundPanner.rolloffFactor = 1;
  33596. this._soundPanner.panningModel = this._panningModel;
  33597. }
  33598. else {
  33599. this._soundPanner.distanceModel = this.distanceModel;
  33600. this._soundPanner.maxDistance = this.maxDistance;
  33601. this._soundPanner.refDistance = this.refDistance;
  33602. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33603. this._soundPanner.panningModel = this._panningModel;
  33604. }
  33605. }
  33606. };
  33607. Sound.prototype.switchPanningModelToHRTF = function () {
  33608. this._panningModel = "HRTF";
  33609. this._switchPanningModel();
  33610. };
  33611. Sound.prototype.switchPanningModelToEqualPower = function () {
  33612. this._panningModel = "equalpower";
  33613. this._switchPanningModel();
  33614. };
  33615. Sound.prototype._switchPanningModel = function () {
  33616. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33617. this._soundPanner.panningModel = this._panningModel;
  33618. }
  33619. };
  33620. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33622. if (this._isOutputConnected) {
  33623. this._ouputAudioNode.disconnect();
  33624. }
  33625. this._ouputAudioNode.connect(soundTrackAudioNode);
  33626. this._isOutputConnected = true;
  33627. }
  33628. };
  33629. /**
  33630. * Transform this sound into a directional source
  33631. * @param coneInnerAngle Size of the inner cone in degree
  33632. * @param coneOuterAngle Size of the outer cone in degree
  33633. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33634. */
  33635. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33636. if (coneOuterAngle < coneInnerAngle) {
  33637. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33638. return;
  33639. }
  33640. this._coneInnerAngle = coneInnerAngle;
  33641. this._coneOuterAngle = coneOuterAngle;
  33642. this._coneOuterGain = coneOuterGain;
  33643. this._isDirectional = true;
  33644. if (this.isPlaying && this.loop) {
  33645. this.stop();
  33646. this.play();
  33647. }
  33648. };
  33649. Sound.prototype.setPosition = function (newPosition) {
  33650. this._position = newPosition;
  33651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33652. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33653. }
  33654. };
  33655. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33656. this._localDirection = newLocalDirection;
  33657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33658. this._updateDirection();
  33659. }
  33660. };
  33661. Sound.prototype._updateDirection = function () {
  33662. var mat = this._connectedMesh.getWorldMatrix();
  33663. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33664. direction.normalize();
  33665. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33666. };
  33667. Sound.prototype.updateDistanceFromListener = function () {
  33668. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33669. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33670. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33671. }
  33672. };
  33673. Sound.prototype.setAttenuationFunction = function (callback) {
  33674. this._customAttenuationFunction = callback;
  33675. };
  33676. /**
  33677. * Play the sound
  33678. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33679. */
  33680. Sound.prototype.play = function (time) {
  33681. var _this = this;
  33682. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33683. try {
  33684. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33685. if (!this._soundSource || !this._streamingSource) {
  33686. if (this.spatialSound) {
  33687. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33688. if (this._isDirectional) {
  33689. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33690. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33691. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33692. if (this._connectedMesh) {
  33693. this._updateDirection();
  33694. }
  33695. else {
  33696. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33697. }
  33698. }
  33699. }
  33700. }
  33701. if (this._streaming) {
  33702. if (!this._streamingSource) {
  33703. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33704. this._htmlAudioElement.onended = function () { _this._onended(); };
  33705. this._htmlAudioElement.playbackRate = this._playbackRate;
  33706. }
  33707. this._streamingSource.disconnect();
  33708. this._streamingSource.connect(this._inputAudioNode);
  33709. this._htmlAudioElement.play();
  33710. }
  33711. else {
  33712. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33713. this._soundSource.buffer = this._audioBuffer;
  33714. this._soundSource.connect(this._inputAudioNode);
  33715. this._soundSource.loop = this.loop;
  33716. this._soundSource.playbackRate.value = this._playbackRate;
  33717. this._soundSource.onended = function () { _this._onended(); };
  33718. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33719. }
  33720. this._startTime = startTime;
  33721. this.isPlaying = true;
  33722. this.isPaused = false;
  33723. }
  33724. catch (ex) {
  33725. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33726. }
  33727. }
  33728. };
  33729. Sound.prototype._onended = function () {
  33730. this.isPlaying = false;
  33731. if (this.onended) {
  33732. this.onended();
  33733. }
  33734. };
  33735. /**
  33736. * Stop the sound
  33737. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33738. */
  33739. Sound.prototype.stop = function (time) {
  33740. if (this.isPlaying) {
  33741. if (this._streaming) {
  33742. this._htmlAudioElement.pause();
  33743. // Test needed for Firefox or it will generate an Invalid State Error
  33744. if (this._htmlAudioElement.currentTime > 0) {
  33745. this._htmlAudioElement.currentTime = 0;
  33746. }
  33747. }
  33748. else {
  33749. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33750. this._soundSource.stop(stopTime);
  33751. }
  33752. this.isPlaying = false;
  33753. }
  33754. };
  33755. Sound.prototype.pause = function () {
  33756. if (this.isPlaying) {
  33757. if (this._streaming) {
  33758. this._htmlAudioElement.pause();
  33759. }
  33760. else {
  33761. this.stop(0);
  33762. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33763. }
  33764. this.isPaused = true;
  33765. }
  33766. };
  33767. Sound.prototype.setVolume = function (newVolume, time) {
  33768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33769. if (time) {
  33770. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33771. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33772. }
  33773. else {
  33774. this._soundGain.gain.value = newVolume;
  33775. }
  33776. }
  33777. this._volume = newVolume;
  33778. };
  33779. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33780. this._playbackRate = newPlaybackRate;
  33781. if (this.isPlaying) {
  33782. if (this._streaming) {
  33783. this._htmlAudioElement.playbackRate = this._playbackRate;
  33784. }
  33785. else {
  33786. this._soundSource.playbackRate.value = this._playbackRate;
  33787. }
  33788. }
  33789. };
  33790. Sound.prototype.getVolume = function () {
  33791. return this._volume;
  33792. };
  33793. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33794. var _this = this;
  33795. this._connectedMesh = meshToConnectTo;
  33796. if (!this.spatialSound) {
  33797. this.spatialSound = true;
  33798. this._createSpatialParameters();
  33799. if (this.isPlaying && this.loop) {
  33800. this.stop();
  33801. this.play();
  33802. }
  33803. }
  33804. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33805. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33806. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33807. };
  33808. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33809. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33810. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33811. this._updateDirection();
  33812. }
  33813. };
  33814. return Sound;
  33815. })();
  33816. BABYLON.Sound = Sound;
  33817. })(BABYLON || (BABYLON = {}));
  33818. var BABYLON;
  33819. (function (BABYLON) {
  33820. var SoundTrack = (function () {
  33821. function SoundTrack(scene, options) {
  33822. this.id = -1;
  33823. this._isMainTrack = false;
  33824. this._isInitialized = false;
  33825. this._scene = scene;
  33826. this.soundCollection = new Array();
  33827. this._options = options;
  33828. if (!this._isMainTrack) {
  33829. this._scene.soundTracks.push(this);
  33830. this.id = this._scene.soundTracks.length - 1;
  33831. }
  33832. }
  33833. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33834. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33835. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33836. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33837. if (this._options) {
  33838. if (this._options.volume) {
  33839. this._outputAudioNode.gain.value = this._options.volume;
  33840. }
  33841. if (this._options.mainTrack) {
  33842. this._isMainTrack = this._options.mainTrack;
  33843. }
  33844. }
  33845. this._isInitialized = true;
  33846. }
  33847. };
  33848. SoundTrack.prototype.dispose = function () {
  33849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33850. if (this._connectedAnalyser) {
  33851. this._connectedAnalyser.stopDebugCanvas();
  33852. }
  33853. while (this.soundCollection.length) {
  33854. this.soundCollection[0].dispose();
  33855. }
  33856. if (this._outputAudioNode) {
  33857. this._outputAudioNode.disconnect();
  33858. }
  33859. this._outputAudioNode = null;
  33860. }
  33861. };
  33862. SoundTrack.prototype.AddSound = function (sound) {
  33863. if (!this._isInitialized) {
  33864. this._initializeSoundTrackAudioGraph();
  33865. }
  33866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33867. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33868. }
  33869. if (sound.soundTrackId) {
  33870. if (sound.soundTrackId === -1) {
  33871. this._scene.mainSoundTrack.RemoveSound(sound);
  33872. }
  33873. else {
  33874. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33875. }
  33876. }
  33877. this.soundCollection.push(sound);
  33878. sound.soundTrackId = this.id;
  33879. };
  33880. SoundTrack.prototype.RemoveSound = function (sound) {
  33881. var index = this.soundCollection.indexOf(sound);
  33882. if (index !== -1) {
  33883. this.soundCollection.splice(index, 1);
  33884. }
  33885. };
  33886. SoundTrack.prototype.setVolume = function (newVolume) {
  33887. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33888. this._outputAudioNode.gain.value = newVolume;
  33889. }
  33890. };
  33891. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33893. for (var i = 0; i < this.soundCollection.length; i++) {
  33894. this.soundCollection[i].switchPanningModelToHRTF();
  33895. }
  33896. }
  33897. };
  33898. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33900. for (var i = 0; i < this.soundCollection.length; i++) {
  33901. this.soundCollection[i].switchPanningModelToEqualPower();
  33902. }
  33903. }
  33904. };
  33905. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33906. if (this._connectedAnalyser) {
  33907. this._connectedAnalyser.stopDebugCanvas();
  33908. }
  33909. this._connectedAnalyser = analyser;
  33910. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33911. this._outputAudioNode.disconnect();
  33912. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33913. }
  33914. };
  33915. return SoundTrack;
  33916. })();
  33917. BABYLON.SoundTrack = SoundTrack;
  33918. })(BABYLON || (BABYLON = {}));
  33919. var BABYLON;
  33920. (function (BABYLON) {
  33921. var DepthRenderer = (function () {
  33922. function DepthRenderer(scene, type) {
  33923. var _this = this;
  33924. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  33925. this._viewMatrix = BABYLON.Matrix.Zero();
  33926. this._projectionMatrix = BABYLON.Matrix.Zero();
  33927. this._transformMatrix = BABYLON.Matrix.Zero();
  33928. this._worldViewProjection = BABYLON.Matrix.Zero();
  33929. this._scene = scene;
  33930. var engine = scene.getEngine();
  33931. // Render target
  33932. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  33933. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33934. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33935. this._depthMap.refreshRate = 1;
  33936. this._depthMap.renderParticles = false;
  33937. this._depthMap.renderList = null;
  33938. // set default depth value to 1.0 (far away)
  33939. this._depthMap.onClear = function (engine) {
  33940. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  33941. };
  33942. // Custom render function
  33943. var renderSubMesh = function (subMesh) {
  33944. var mesh = subMesh.getRenderingMesh();
  33945. var scene = _this._scene;
  33946. var engine = scene.getEngine();
  33947. // Culling
  33948. engine.setState(subMesh.getMaterial().backFaceCulling);
  33949. // Managing instances
  33950. var batch = mesh._getInstancesRenderList(subMesh._id);
  33951. if (batch.mustReturn) {
  33952. return;
  33953. }
  33954. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33955. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33956. engine.enableEffect(_this._effect);
  33957. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  33958. var material = subMesh.getMaterial();
  33959. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33960. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  33961. // Alpha test
  33962. if (material && material.needAlphaTesting()) {
  33963. var alphaTexture = material.getAlphaTestTexture();
  33964. _this._effect.setTexture("diffuseSampler", alphaTexture);
  33965. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33966. }
  33967. // Bones
  33968. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33969. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33970. }
  33971. // Draw
  33972. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33973. }
  33974. };
  33975. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  33976. var index;
  33977. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33978. renderSubMesh(opaqueSubMeshes.data[index]);
  33979. }
  33980. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33981. renderSubMesh(alphaTestSubMeshes.data[index]);
  33982. }
  33983. };
  33984. }
  33985. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  33986. var defines = [];
  33987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33988. var mesh = subMesh.getMesh();
  33989. var scene = mesh.getScene();
  33990. var material = subMesh.getMaterial();
  33991. // Alpha test
  33992. if (material && material.needAlphaTesting()) {
  33993. defines.push("#define ALPHATEST");
  33994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33995. attribs.push(BABYLON.VertexBuffer.UVKind);
  33996. defines.push("#define UV1");
  33997. }
  33998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34000. defines.push("#define UV2");
  34001. }
  34002. }
  34003. // Bones
  34004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34007. defines.push("#define BONES");
  34008. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34009. }
  34010. // Instances
  34011. if (useInstances) {
  34012. defines.push("#define INSTANCES");
  34013. attribs.push("world0");
  34014. attribs.push("world1");
  34015. attribs.push("world2");
  34016. attribs.push("world3");
  34017. }
  34018. // Get correct effect
  34019. var join = defines.join("\n");
  34020. if (this._cachedDefines !== join) {
  34021. this._cachedDefines = join;
  34022. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34023. }
  34024. return this._effect.isReady();
  34025. };
  34026. DepthRenderer.prototype.getDepthMap = function () {
  34027. return this._depthMap;
  34028. };
  34029. // Methods
  34030. DepthRenderer.prototype.dispose = function () {
  34031. this._depthMap.dispose();
  34032. };
  34033. return DepthRenderer;
  34034. })();
  34035. BABYLON.DepthRenderer = DepthRenderer;
  34036. })(BABYLON || (BABYLON = {}));
  34037. var BABYLON;
  34038. (function (BABYLON) {
  34039. var SSAORenderingPipeline = (function (_super) {
  34040. __extends(SSAORenderingPipeline, _super);
  34041. /**
  34042. * @constructor
  34043. * @param {string} name - The rendering pipeline name
  34044. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34045. * @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 }
  34046. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34047. */
  34048. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34049. var _this = this;
  34050. _super.call(this, scene.getEngine(), name);
  34051. // Members
  34052. /**
  34053. * The PassPostProcess id in the pipeline that contains the original scene color
  34054. * @type {string}
  34055. */
  34056. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34057. /**
  34058. * The SSAO PostProcess id in the pipeline
  34059. * @type {string}
  34060. */
  34061. this.SSAORenderEffect = "SSAORenderEffect";
  34062. /**
  34063. * The horizontal blur PostProcess id in the pipeline
  34064. * @type {string}
  34065. */
  34066. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34067. /**
  34068. * The vertical blur PostProcess id in the pipeline
  34069. * @type {string}
  34070. */
  34071. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34072. /**
  34073. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34074. * @type {string}
  34075. */
  34076. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34077. /**
  34078. * The output strength of the SSAO post-process. Default value is 1.0.
  34079. * @type {number}
  34080. */
  34081. this.totalStrength = 1.0;
  34082. /**
  34083. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  34084. * @type {number}
  34085. */
  34086. this.radius = 0.0002;
  34087. /**
  34088. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34089. * Must not be equal to fallOff and superior to fallOff.
  34090. * Default value is 0.0075
  34091. * @type {number}
  34092. */
  34093. this.area = 0.0075;
  34094. /**
  34095. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34096. * Must not be equal to area and inferior to area.
  34097. * Default value is 0.0002
  34098. * @type {number}
  34099. */
  34100. this.fallOff = 0.0002;
  34101. this._firstUpdate = true;
  34102. this._scene = scene;
  34103. // Set up assets
  34104. this._createRandomTexture();
  34105. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34106. var ssaoRatio = ratio.ssaoRatio || ratio;
  34107. var combineRatio = ratio.combineRatio || ratio;
  34108. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34109. this._createSSAOPostProcess(ssaoRatio);
  34110. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34111. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 4.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34112. this._createSSAOCombinePostProcess(combineRatio);
  34113. // Set up pipeline
  34114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34117. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34119. // Finish
  34120. scene.postProcessRenderPipelineManager.addPipeline(this);
  34121. if (cameras)
  34122. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34123. }
  34124. // Public Methods
  34125. /**
  34126. * Returns the horizontal blur PostProcess
  34127. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34128. */
  34129. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34130. return this._blurHPostProcess;
  34131. };
  34132. /**
  34133. * Returns the vertical blur PostProcess
  34134. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34135. */
  34136. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34137. return this._blurVPostProcess;
  34138. };
  34139. /**
  34140. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34141. */
  34142. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34143. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34144. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34145. this._originalColorPostProcess = undefined;
  34146. this._ssaoPostProcess = undefined;
  34147. this._blurHPostProcess = undefined;
  34148. this._blurVPostProcess = undefined;
  34149. this._ssaoCombinePostProcess = undefined;
  34150. this._randomTexture.dispose();
  34151. if (disableDepthRender)
  34152. this._scene.disableDepthRenderer();
  34153. };
  34154. // Private Methods
  34155. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34156. var _this = this;
  34157. var sampleSphere = [
  34158. 0.5381, 0.1856, -0.4319,
  34159. 0.1379, 0.2486, 0.4430,
  34160. 0.3371, 0.5679, -0.0057,
  34161. -0.6999, -0.0451, -0.0019,
  34162. 0.0689, -0.1598, -0.8547,
  34163. 0.0560, 0.0069, -0.1843,
  34164. -0.0146, 0.1402, 0.0762,
  34165. 0.0100, -0.1924, -0.0344,
  34166. -0.3577, -0.5301, -0.4358,
  34167. -0.3169, 0.1063, 0.0158,
  34168. 0.0103, -0.5869, 0.0046,
  34169. -0.0897, -0.4940, 0.3287,
  34170. 0.7119, -0.0154, -0.0918,
  34171. -0.0533, 0.0596, -0.5411,
  34172. 0.0352, -0.0631, 0.5460,
  34173. -0.4776, 0.2847, -0.0271
  34174. ];
  34175. var samplesFactor = 1.0 / 16.0;
  34176. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34177. this._ssaoPostProcess.onApply = function (effect) {
  34178. if (_this._firstUpdate) {
  34179. effect.setArray3("sampleSphere", sampleSphere);
  34180. effect.setFloat("samplesFactor", samplesFactor);
  34181. effect.setFloat("randTextureTiles", 4.0);
  34182. _this._firstUpdate = false;
  34183. }
  34184. effect.setFloat("totalStrength", _this.totalStrength);
  34185. effect.setFloat("radius", _this.radius);
  34186. effect.setFloat("area", _this.area);
  34187. effect.setFloat("fallOff", _this.fallOff);
  34188. effect.setTexture("textureSampler", _this._depthTexture);
  34189. effect.setTexture("randomSampler", _this._randomTexture);
  34190. };
  34191. };
  34192. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34193. var _this = this;
  34194. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34195. this._ssaoCombinePostProcess.onApply = function (effect) {
  34196. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34197. };
  34198. };
  34199. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34200. var size = 512;
  34201. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34202. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34203. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34204. var context = this._randomTexture.getContext();
  34205. var rand = function (min, max) {
  34206. return Math.random() * (max - min) + min;
  34207. };
  34208. for (var x = 0; x < size; x++) {
  34209. for (var y = 0; y < size; y++) {
  34210. var randVector = BABYLON.Vector3.Zero();
  34211. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  34212. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  34213. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  34214. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34215. context.fillRect(x, y, 1, 1);
  34216. }
  34217. }
  34218. this._randomTexture.update(false);
  34219. };
  34220. return SSAORenderingPipeline;
  34221. })(BABYLON.PostProcessRenderPipeline);
  34222. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34223. })(BABYLON || (BABYLON = {}));
  34224. var BABYLON;
  34225. (function (BABYLON) {
  34226. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34227. var VolumetricLightScatteringPostProcess = (function (_super) {
  34228. __extends(VolumetricLightScatteringPostProcess, _super);
  34229. /**
  34230. * @constructor
  34231. * @param {string} name - The post-process name
  34232. * @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)
  34233. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34234. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34235. * @param {number} samples - The post-process quality, default 100
  34236. * @param {number} samplingMode - The post-process filtering mode
  34237. * @param {BABYLON.Engine} engine - The babylon engine
  34238. * @param {boolean} reusable - If the post-process is reusable
  34239. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34240. */
  34241. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34242. var _this = this;
  34243. if (samples === void 0) { samples = 100; }
  34244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34245. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34246. this._screenCoordinates = BABYLON.Vector2.Zero();
  34247. /**
  34248. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34249. * @type {boolean}
  34250. */
  34251. this.useCustomMeshPosition = false;
  34252. /**
  34253. * If the post-process should inverse the light scattering direction
  34254. * @type {boolean}
  34255. */
  34256. this.invert = true;
  34257. /**
  34258. * Set to true to use the diffuseColor instead of the diffuseTexture
  34259. * @type {boolean}
  34260. */
  34261. this.useDiffuseColor = false;
  34262. /**
  34263. * Array containing the excluded meshes not rendered in the internal pass
  34264. */
  34265. this.excludedMeshes = new Array();
  34266. /**
  34267. * Controls the overall intensity of the post-process
  34268. * @type {number}
  34269. */
  34270. this.exposure = 0.3;
  34271. /**
  34272. * Dissipates each sample's contribution in range [0, 1]
  34273. * @type {number}
  34274. */
  34275. this.decay = 0.96815;
  34276. /**
  34277. * Controls the overall intensity of each sample
  34278. * @type {number}
  34279. */
  34280. this.weight = 0.58767;
  34281. /**
  34282. * Controls the density of each sample
  34283. * @type {number}
  34284. */
  34285. this.density = 0.926;
  34286. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34287. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34288. // Configure mesh
  34289. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34290. // Configure
  34291. this._createPass(scene, ratio.passRatio || ratio);
  34292. this.onApply = function (effect) {
  34293. _this._updateMeshScreenCoordinates(scene);
  34294. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34295. effect.setFloat("exposure", _this.exposure);
  34296. effect.setFloat("decay", _this.decay);
  34297. effect.setFloat("weight", _this.weight);
  34298. effect.setFloat("density", _this.density);
  34299. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34300. };
  34301. }
  34302. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34303. var mesh = subMesh.getMesh();
  34304. var defines = [];
  34305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34306. var material = subMesh.getMaterial();
  34307. var needUV = false;
  34308. // Render this.mesh as default
  34309. if (mesh === this.mesh) {
  34310. if (this.useDiffuseColor) {
  34311. defines.push("#define DIFFUSE_COLOR_RENDER");
  34312. }
  34313. else if (material) {
  34314. if (material.diffuseTexture !== undefined) {
  34315. defines.push("#define BASIC_RENDER");
  34316. }
  34317. else {
  34318. defines.push("#define DIFFUSE_COLOR_RENDER");
  34319. }
  34320. }
  34321. defines.push("#define NEED_UV");
  34322. needUV = true;
  34323. }
  34324. // Alpha test
  34325. if (material) {
  34326. if (material.needAlphaTesting()) {
  34327. defines.push("#define ALPHATEST");
  34328. }
  34329. if (material.opacityTexture !== undefined) {
  34330. defines.push("#define OPACITY");
  34331. if (material.opacityTexture.getAlphaFromRGB) {
  34332. defines.push("#define OPACITYRGB");
  34333. }
  34334. if (!needUV) {
  34335. defines.push("#define NEED_UV");
  34336. }
  34337. }
  34338. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34339. attribs.push(BABYLON.VertexBuffer.UVKind);
  34340. defines.push("#define UV1");
  34341. }
  34342. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34343. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34344. defines.push("#define UV2");
  34345. }
  34346. }
  34347. // Bones
  34348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34351. defines.push("#define BONES");
  34352. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34353. }
  34354. // Instances
  34355. if (useInstances) {
  34356. defines.push("#define INSTANCES");
  34357. attribs.push("world0");
  34358. attribs.push("world1");
  34359. attribs.push("world2");
  34360. attribs.push("world3");
  34361. }
  34362. // Get correct effect
  34363. var join = defines.join("\n");
  34364. if (this._cachedDefines !== join) {
  34365. this._cachedDefines = join;
  34366. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34367. }
  34368. return this._volumetricLightScatteringPass.isReady();
  34369. };
  34370. /**
  34371. * Sets the new light position for light scattering effect
  34372. * @param {BABYLON.Vector3} The new custom light position
  34373. */
  34374. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34375. this._customMeshPosition = position;
  34376. };
  34377. /**
  34378. * Returns the light position for light scattering effect
  34379. * @return {BABYLON.Vector3} The custom light position
  34380. */
  34381. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34382. return this._customMeshPosition;
  34383. };
  34384. /**
  34385. * Disposes the internal assets and detaches the post-process from the camera
  34386. */
  34387. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34388. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34389. if (rttIndex !== -1) {
  34390. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34391. }
  34392. this._volumetricLightScatteringRTT.dispose();
  34393. _super.prototype.dispose.call(this, camera);
  34394. };
  34395. /**
  34396. * Returns the render target texture used by the post-process
  34397. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34398. */
  34399. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34400. return this._volumetricLightScatteringRTT;
  34401. };
  34402. // Private methods
  34403. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34404. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34405. return true;
  34406. }
  34407. return false;
  34408. };
  34409. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34410. var _this = this;
  34411. var engine = scene.getEngine();
  34412. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34413. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34414. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34415. this._volumetricLightScatteringRTT.renderList = null;
  34416. this._volumetricLightScatteringRTT.renderParticles = false;
  34417. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34418. // Custom render function for submeshes
  34419. var renderSubMesh = function (subMesh) {
  34420. var mesh = subMesh.getRenderingMesh();
  34421. if (_this._meshExcluded(mesh)) {
  34422. return;
  34423. }
  34424. var scene = mesh.getScene();
  34425. var engine = scene.getEngine();
  34426. // Culling
  34427. engine.setState(subMesh.getMaterial().backFaceCulling);
  34428. // Managing instances
  34429. var batch = mesh._getInstancesRenderList(subMesh._id);
  34430. if (batch.mustReturn) {
  34431. return;
  34432. }
  34433. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34434. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34435. engine.enableEffect(_this._volumetricLightScatteringPass);
  34436. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34437. var material = subMesh.getMaterial();
  34438. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34439. // Alpha test
  34440. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34441. var alphaTexture = material.getAlphaTestTexture();
  34442. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34443. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34444. }
  34445. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34446. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34447. if (alphaTexture) {
  34448. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34449. }
  34450. }
  34451. if (material.opacityTexture !== undefined) {
  34452. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34453. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34454. }
  34455. }
  34456. // Bones
  34457. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34458. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34459. }
  34460. // Draw
  34461. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34462. }
  34463. };
  34464. // Render target texture callbacks
  34465. var savedSceneClearColor;
  34466. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34467. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34468. savedSceneClearColor = scene.clearColor;
  34469. scene.clearColor = sceneClearColor;
  34470. };
  34471. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34472. scene.clearColor = savedSceneClearColor;
  34473. };
  34474. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34475. var engine = scene.getEngine();
  34476. var index;
  34477. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34478. renderSubMesh(opaqueSubMeshes.data[index]);
  34479. }
  34480. engine.setAlphaTesting(true);
  34481. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34482. renderSubMesh(alphaTestSubMeshes.data[index]);
  34483. }
  34484. engine.setAlphaTesting(false);
  34485. if (transparentSubMeshes.length) {
  34486. // Sort sub meshes
  34487. for (index = 0; index < transparentSubMeshes.length; index++) {
  34488. var submesh = transparentSubMeshes.data[index];
  34489. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34490. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34491. }
  34492. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34493. sortedArray.sort(function (a, b) {
  34494. // Alpha index first
  34495. if (a._alphaIndex > b._alphaIndex) {
  34496. return 1;
  34497. }
  34498. if (a._alphaIndex < b._alphaIndex) {
  34499. return -1;
  34500. }
  34501. // Then distance to camera
  34502. if (a._distanceToCamera < b._distanceToCamera) {
  34503. return 1;
  34504. }
  34505. if (a._distanceToCamera > b._distanceToCamera) {
  34506. return -1;
  34507. }
  34508. return 0;
  34509. });
  34510. // Render sub meshes
  34511. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34512. for (index = 0; index < sortedArray.length; index++) {
  34513. renderSubMesh(sortedArray[index]);
  34514. }
  34515. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34516. }
  34517. };
  34518. };
  34519. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34520. var transform = scene.getTransformMatrix();
  34521. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34522. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34523. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34524. if (this.invert)
  34525. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34526. };
  34527. // Static methods
  34528. /**
  34529. * Creates a default mesh for the Volumeric Light Scattering post-process
  34530. * @param {string} The mesh name
  34531. * @param {BABYLON.Scene} The scene where to create the mesh
  34532. * @return {BABYLON.Mesh} the default mesh
  34533. */
  34534. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34535. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34536. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34537. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34538. return mesh;
  34539. };
  34540. return VolumetricLightScatteringPostProcess;
  34541. })(BABYLON.PostProcess);
  34542. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34543. })(BABYLON || (BABYLON = {}));
  34544. var BABYLON;
  34545. (function (BABYLON) {
  34546. var LensRenderingPipeline = (function (_super) {
  34547. __extends(LensRenderingPipeline, _super);
  34548. /**
  34549. * @constructor
  34550. *
  34551. * Effect parameters are as follow:
  34552. * {
  34553. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34554. * edge_blur: number; // from 0 to x (1 for realism)
  34555. * distortion: number; // from 0 to x (1 for realism)
  34556. * grain_amount: number; // from 0 to 1
  34557. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34558. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34559. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34560. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34561. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34562. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34563. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34564. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34565. * }
  34566. * Note: if an effect parameter is unset, effect is disabled
  34567. *
  34568. * @param {string} name - The rendering pipeline name
  34569. * @param {object} parameters - An object containing all parameters (see above)
  34570. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34571. * @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)
  34572. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34573. */
  34574. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34575. var _this = this;
  34576. if (ratio === void 0) { ratio = 1.0; }
  34577. _super.call(this, scene.getEngine(), name);
  34578. // Lens effects can be of the following:
  34579. // - chromatic aberration (slight shift of RGB colors)
  34580. // - blur on the edge of the lens
  34581. // - lens distortion
  34582. // - depth-of-field blur & highlights enhancing
  34583. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34584. // - grain effect (noise or custom texture)
  34585. // Two additional texture samplers are needed:
  34586. // - depth map (for depth-of-field)
  34587. // - grain texture
  34588. /**
  34589. * The chromatic aberration PostProcess id in the pipeline
  34590. * @type {string}
  34591. */
  34592. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34593. /**
  34594. * The highlights enhancing PostProcess id in the pipeline
  34595. * @type {string}
  34596. */
  34597. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34598. /**
  34599. * The depth-of-field PostProcess id in the pipeline
  34600. * @type {string}
  34601. */
  34602. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34603. this._scene = scene;
  34604. // Fetch texture samplers
  34605. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34606. if (parameters.grain_texture) {
  34607. this._grainTexture = parameters.grain_texture;
  34608. }
  34609. else {
  34610. this._createGrainTexture();
  34611. }
  34612. // save parameters
  34613. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34614. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34615. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34616. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34617. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34618. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34619. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34620. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34621. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34622. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34623. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34624. // Create effects
  34625. this._createChromaticAberrationPostProcess(ratio);
  34626. this._createHighlightsPostProcess(ratio);
  34627. this._createDepthOfFieldPostProcess(ratio / 4);
  34628. // Set up pipeline
  34629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34631. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34632. if (this._highlightsGain === -1) {
  34633. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34634. }
  34635. // Finish
  34636. scene.postProcessRenderPipelineManager.addPipeline(this);
  34637. if (cameras) {
  34638. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34639. }
  34640. }
  34641. // public methods (self explanatory)
  34642. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34643. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34644. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34645. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34646. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34647. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34648. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34649. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34650. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34651. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34652. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34653. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34654. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  34655. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  34656. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34657. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34658. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34659. this._highlightsGain = amount;
  34660. };
  34661. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34662. if (this._highlightsGain === -1) {
  34663. this._highlightsGain = 1.0;
  34664. }
  34665. this._highlightsThreshold = amount;
  34666. };
  34667. LensRenderingPipeline.prototype.disableHighlights = function () {
  34668. this._highlightsGain = -1;
  34669. };
  34670. /**
  34671. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34672. */
  34673. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34674. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34676. this._chromaticAberrationPostProcess = undefined;
  34677. this._highlightsPostProcess = undefined;
  34678. this._depthOfFieldPostProcess = undefined;
  34679. this._grainTexture.dispose();
  34680. if (disableDepthRender)
  34681. this._scene.disableDepthRenderer();
  34682. };
  34683. // colors shifting and distortion
  34684. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34685. var _this = this;
  34686. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34687. [], // samplers
  34688. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34689. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34690. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34693. };
  34694. };
  34695. // highlights enhancing
  34696. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34697. var _this = this;
  34698. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  34699. [], // samplers
  34700. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34701. this._highlightsPostProcess.onApply = function (effect) {
  34702. effect.setFloat('gain', _this._highlightsGain);
  34703. effect.setFloat('threshold', _this._highlightsThreshold);
  34704. effect.setBool('pentagon', _this._dofPentagon);
  34705. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34706. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34707. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34708. };
  34709. };
  34710. // colors shifting and distortion
  34711. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34712. var _this = this;
  34713. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34714. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34715. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34716. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34717. this._depthOfFieldPostProcess.onApply = function (effect) {
  34718. effect.setTexture("depthSampler", _this._depthTexture);
  34719. effect.setTexture("grainSampler", _this._grainTexture);
  34720. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34721. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34722. effect.setFloat('grain_amount', _this._grainAmount);
  34723. effect.setBool('blur_noise', _this._blurNoise);
  34724. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34725. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34726. effect.setFloat('distortion', _this._distortion);
  34727. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34728. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34729. effect.setFloat('aperture', _this._dofAperture);
  34730. effect.setFloat('darken', _this._dofDarken);
  34731. effect.setFloat('edge_blur', _this._edgeBlur);
  34732. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34733. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34734. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34735. };
  34736. };
  34737. // creates a black and white random noise texture, 512x512
  34738. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34739. var size = 512;
  34740. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34741. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34742. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34743. var context = this._grainTexture.getContext();
  34744. var rand = function (min, max) {
  34745. return Math.random() * (max - min) + min;
  34746. };
  34747. var value;
  34748. for (var x = 0; x < size; x++) {
  34749. for (var y = 0; y < size; y++) {
  34750. value = Math.floor(rand(0.42, 0.58) * 255);
  34751. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34752. context.fillRect(x, y, 1, 1);
  34753. }
  34754. }
  34755. this._grainTexture.update(false);
  34756. };
  34757. return LensRenderingPipeline;
  34758. })(BABYLON.PostProcessRenderPipeline);
  34759. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34760. })(BABYLON || (BABYLON = {}));
  34761. //
  34762. // This post-process allows the modification of rendered colors by using
  34763. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34764. //
  34765. // The object needs to be provided an url to a texture containing the color
  34766. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34767. // Use an image editing software to tweak the LUT to match your needs.
  34768. //
  34769. // For an example of a color LUT, see here:
  34770. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34771. // For explanations on color grading, see here:
  34772. // http://udn.epicgames.com/Three/ColorGrading.html
  34773. //
  34774. var BABYLON;
  34775. (function (BABYLON) {
  34776. var ColorCorrectionPostProcess = (function (_super) {
  34777. __extends(ColorCorrectionPostProcess, _super);
  34778. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34779. var _this = this;
  34780. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34781. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34782. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34783. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34784. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34785. this.onApply = function (effect) {
  34786. effect.setTexture("colorTable", _this._colorTableTexture);
  34787. };
  34788. }
  34789. return ColorCorrectionPostProcess;
  34790. })(BABYLON.PostProcess);
  34791. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34792. })(BABYLON || (BABYLON = {}));
  34793. var BABYLON;
  34794. (function (BABYLON) {
  34795. var AnaglyphFreeCamera = (function (_super) {
  34796. __extends(AnaglyphFreeCamera, _super);
  34797. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34798. _super.call(this, name, position, scene);
  34799. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34800. }
  34801. return AnaglyphFreeCamera;
  34802. })(BABYLON.FreeCamera);
  34803. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34804. var AnaglyphArcRotateCamera = (function (_super) {
  34805. __extends(AnaglyphArcRotateCamera, _super);
  34806. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34807. _super.call(this, name, alpha, beta, radius, target, scene);
  34808. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34809. }
  34810. return AnaglyphArcRotateCamera;
  34811. })(BABYLON.ArcRotateCamera);
  34812. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34813. var AnaglyphGamepadCamera = (function (_super) {
  34814. __extends(AnaglyphGamepadCamera, _super);
  34815. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34816. _super.call(this, name, position, scene);
  34817. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34818. }
  34819. return AnaglyphGamepadCamera;
  34820. })(BABYLON.GamepadCamera);
  34821. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34822. var StereoscopicFreeCamera = (function (_super) {
  34823. __extends(StereoscopicFreeCamera, _super);
  34824. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34825. _super.call(this, name, position, scene);
  34826. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34827. }
  34828. return StereoscopicFreeCamera;
  34829. })(BABYLON.FreeCamera);
  34830. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34831. var StereoscopicArcRotateCamera = (function (_super) {
  34832. __extends(StereoscopicArcRotateCamera, _super);
  34833. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34834. _super.call(this, name, alpha, beta, radius, target, scene);
  34835. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34836. }
  34837. return StereoscopicArcRotateCamera;
  34838. })(BABYLON.ArcRotateCamera);
  34839. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34840. var StereoscopicGamepadCamera = (function (_super) {
  34841. __extends(StereoscopicGamepadCamera, _super);
  34842. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34843. _super.call(this, name, position, scene);
  34844. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34845. }
  34846. return StereoscopicGamepadCamera;
  34847. })(BABYLON.GamepadCamera);
  34848. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  34849. })(BABYLON || (BABYLON = {}));
  34850. var BABYLON;
  34851. (function (BABYLON) {
  34852. var HDRRenderingPipeline = (function (_super) {
  34853. __extends(HDRRenderingPipeline, _super);
  34854. /**
  34855. * @constructor
  34856. * @param {string} name - The rendering pipeline name
  34857. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34858. * @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)
  34859. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  34860. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34861. */
  34862. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  34863. var _this = this;
  34864. if (originalPostProcess === void 0) { originalPostProcess = null; }
  34865. _super.call(this, scene.getEngine(), name);
  34866. /**
  34867. * Public members
  34868. */
  34869. // Gaussian Blur
  34870. /**
  34871. * Gaussian blur coefficient
  34872. * @type {number}
  34873. */
  34874. this.gaussCoeff = 0.3;
  34875. /**
  34876. * Gaussian blur mean
  34877. * @type {number}
  34878. */
  34879. this.gaussMean = 1.0;
  34880. /**
  34881. * Gaussian blur standard deviation
  34882. * @type {number}
  34883. */
  34884. this.gaussStandDev = 0.8;
  34885. // HDR
  34886. /**
  34887. * Exposure, controls the overall intensity of the pipeline
  34888. * @type {number}
  34889. */
  34890. this.exposure = 1.0;
  34891. /**
  34892. * Minimum luminance that the post-process can output. Luminance is >= 0
  34893. * @type {number}
  34894. */
  34895. this.minimumLuminance = 1.0;
  34896. /**
  34897. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  34898. * @type {number}
  34899. */
  34900. this.maximumLuminance = 1e20;
  34901. /**
  34902. * Increase rate for luminance: eye adaptation speed to dark
  34903. * @type {number}
  34904. */
  34905. this.luminanceIncreaserate = 0.5;
  34906. /**
  34907. * Decrease rate for luminance: eye adaptation speed to bright
  34908. * @type {number}
  34909. */
  34910. this.luminanceDecreaseRate = 0.5;
  34911. // Bright pass
  34912. /**
  34913. * Minimum luminance needed to compute HDR
  34914. * @type {number}
  34915. */
  34916. this.brightThreshold = 0.8;
  34917. this._needUpdate = true;
  34918. this._scene = scene;
  34919. // Bright pass
  34920. this._createBrightPassPostProcess(scene, ratio);
  34921. // Down sample X4
  34922. this._createDownSampleX4PostProcess(scene, ratio);
  34923. // Create gaussian blur post-processes
  34924. this._createGaussianBlurPostProcess(scene, ratio);
  34925. // Texture adder
  34926. this._createTextureAdderPostProcess(scene, ratio);
  34927. // Luminance generator
  34928. this._createLuminanceGeneratorPostProcess(scene);
  34929. // HDR
  34930. this._createHDRPostProcess(scene, ratio);
  34931. // Pass postprocess
  34932. if (originalPostProcess === null) {
  34933. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34934. }
  34935. else {
  34936. this._originalPostProcess = originalPostProcess;
  34937. }
  34938. // Configure pipeline
  34939. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  34940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  34941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  34942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  34943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  34944. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  34945. var addDownSamplerPostProcess = function (id) {
  34946. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  34947. };
  34948. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34949. addDownSamplerPostProcess(i);
  34950. }
  34951. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  34952. // Finish
  34953. scene.postProcessRenderPipelineManager.addPipeline(this);
  34954. if (cameras !== null) {
  34955. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34956. }
  34957. this.update();
  34958. }
  34959. /**
  34960. * Tells the pipeline to update its post-processes
  34961. */
  34962. HDRRenderingPipeline.prototype.update = function () {
  34963. this._needUpdate = true;
  34964. };
  34965. /**
  34966. * Returns the current calculated luminance
  34967. */
  34968. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  34969. return this._hdrCurrentLuminance;
  34970. };
  34971. /**
  34972. * Returns the currently drawn luminance
  34973. */
  34974. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  34975. return this._hdrOutputLuminance;
  34976. };
  34977. /**
  34978. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  34979. */
  34980. HDRRenderingPipeline.prototype.dispose = function () {
  34981. this._originalPostProcess = undefined;
  34982. this._brightPassPostProcess = undefined;
  34983. this._downSampleX4PostProcess = undefined;
  34984. this._guassianBlurHPostProcess = undefined;
  34985. this._guassianBlurVPostProcess = undefined;
  34986. this._textureAdderPostProcess = undefined;
  34987. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34988. this._downSamplePostProcesses[i] = undefined;
  34989. }
  34990. this._hdrPostProcess = undefined;
  34991. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34992. };
  34993. /**
  34994. * Creates the HDR post-process and computes the luminance adaptation
  34995. */
  34996. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  34997. var _this = this;
  34998. var hdrLastLuminance = 0.0;
  34999. this._hdrOutputLuminance = -1.0;
  35000. this._hdrCurrentLuminance = 1.0;
  35001. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35002. this._hdrPostProcess.onApply = function (effect) {
  35003. if (_this._hdrOutputLuminance < 0.0) {
  35004. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35005. }
  35006. else {
  35007. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35008. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35009. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35010. }
  35011. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35012. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35013. }
  35014. else {
  35015. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35016. }
  35017. }
  35018. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35019. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35020. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35021. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35022. effect.setFloat("exposure", _this.exposure);
  35023. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35024. _this._needUpdate = false;
  35025. };
  35026. };
  35027. /**
  35028. * Texture Adder post-process
  35029. */
  35030. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35031. var _this = this;
  35032. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35033. this._textureAdderPostProcess.onApply = function (effect) {
  35034. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35035. };
  35036. };
  35037. /**
  35038. * Down sample X4 post-process
  35039. */
  35040. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35041. var _this = this;
  35042. var downSampleX4Offsets = new Array(32);
  35043. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35044. this._downSampleX4PostProcess.onApply = function (effect) {
  35045. if (_this._needUpdate) {
  35046. var id = 0;
  35047. for (var i = -2; i < 2; i++) {
  35048. for (var j = -2; j < 2; j++) {
  35049. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35050. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35051. id += 2;
  35052. }
  35053. }
  35054. }
  35055. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35056. };
  35057. };
  35058. /**
  35059. * Bright pass post-process
  35060. */
  35061. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35062. var _this = this;
  35063. var brightOffsets = new Array(8);
  35064. var brightPassCallback = function (effect) {
  35065. if (_this._needUpdate) {
  35066. var sU = (1.0 / _this._brightPassPostProcess.width);
  35067. var sV = (1.0 / _this._brightPassPostProcess.height);
  35068. brightOffsets[0] = -0.5 * sU;
  35069. brightOffsets[1] = 0.5 * sV;
  35070. brightOffsets[2] = 0.5 * sU;
  35071. brightOffsets[3] = 0.5 * sV;
  35072. brightOffsets[4] = -0.5 * sU;
  35073. brightOffsets[5] = -0.5 * sV;
  35074. brightOffsets[6] = 0.5 * sU;
  35075. brightOffsets[7] = -0.5 * sV;
  35076. }
  35077. effect.setArray2("dsOffsets", brightOffsets);
  35078. effect.setFloat("brightThreshold", _this.brightThreshold);
  35079. };
  35080. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35081. this._brightPassPostProcess.onApply = brightPassCallback;
  35082. };
  35083. /**
  35084. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35085. */
  35086. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35087. var _this = this;
  35088. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35089. var luminanceOffsets = new Array(8);
  35090. var downSampleOffsets = new Array(18);
  35091. var halfDestPixelSize;
  35092. this._downSamplePostProcesses = new Array(lumSteps);
  35093. // Utils for luminance
  35094. var luminanceUpdateSourceOffsets = function (width, height) {
  35095. var sU = (1.0 / width);
  35096. var sV = (1.0 / height);
  35097. luminanceOffsets[0] = -0.5 * sU;
  35098. luminanceOffsets[1] = 0.5 * sV;
  35099. luminanceOffsets[2] = 0.5 * sU;
  35100. luminanceOffsets[3] = 0.5 * sV;
  35101. luminanceOffsets[4] = -0.5 * sU;
  35102. luminanceOffsets[5] = -0.5 * sV;
  35103. luminanceOffsets[6] = 0.5 * sU;
  35104. luminanceOffsets[7] = -0.5 * sV;
  35105. };
  35106. var luminanceUpdateDestOffsets = function (width, height) {
  35107. var id = 0;
  35108. for (var x = -1; x < 2; x++) {
  35109. for (var y = -1; y < 2; y++) {
  35110. downSampleOffsets[id] = (x) / width;
  35111. downSampleOffsets[id + 1] = (y) / height;
  35112. id += 2;
  35113. }
  35114. }
  35115. };
  35116. // Luminance callback
  35117. var luminanceCallback = function (effect) {
  35118. if (_this._needUpdate) {
  35119. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35120. }
  35121. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35122. effect.setArray2("lumOffsets", luminanceOffsets);
  35123. };
  35124. // Down sample callbacks
  35125. var downSampleCallback = function (indice) {
  35126. var i = indice;
  35127. return function (effect) {
  35128. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35129. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35130. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35131. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35132. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35133. effect.setArray2("dsOffsets", downSampleOffsets);
  35134. };
  35135. };
  35136. var downSampleAfterRenderCallback = function (effect) {
  35137. // Unpack result
  35138. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35139. 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);
  35140. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35141. };
  35142. // Create luminance post-process
  35143. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35144. 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);
  35145. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35146. // Create down sample post-processes
  35147. for (var i = lumSteps - 2; i >= 0; i--) {
  35148. var length = Math.pow(3, i);
  35149. ratio = { width: length, height: length };
  35150. var defines = "#define DOWN_SAMPLE\n";
  35151. if (i === 0) {
  35152. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35153. }
  35154. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35155. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35156. if (i === 0) {
  35157. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35158. }
  35159. }
  35160. };
  35161. /**
  35162. * Gaussian blur post-processes. Horizontal and Vertical
  35163. */
  35164. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35165. var _this = this;
  35166. var blurOffsetsW = new Array(9);
  35167. var blurOffsetsH = new Array(9);
  35168. var blurWeights = new Array(9);
  35169. var uniforms = ["blurOffsets", "blurWeights"];
  35170. // Utils for gaussian blur
  35171. var calculateBlurOffsets = function (height) {
  35172. var lastOutputDimensions = {
  35173. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  35174. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  35175. };
  35176. for (var i = 0; i < 9; i++) {
  35177. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35178. if (height) {
  35179. blurOffsetsH[i] = value;
  35180. }
  35181. else {
  35182. blurOffsetsW[i] = value;
  35183. }
  35184. }
  35185. };
  35186. var calculateWeights = function () {
  35187. var x = 0.0;
  35188. for (var i = 0; i < 9; i++) {
  35189. x = (i - 4.0) / 4.0;
  35190. 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));
  35191. }
  35192. };
  35193. // Callback
  35194. var gaussianBlurCallback = function (height) {
  35195. return function (effect) {
  35196. if (_this._needUpdate) {
  35197. calculateWeights();
  35198. calculateBlurOffsets(height);
  35199. }
  35200. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35201. effect.setArray("blurWeights", blurWeights);
  35202. };
  35203. };
  35204. // Create horizontal gaussian blur post-processes
  35205. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35206. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35207. // Create vertical gaussian blur post-process
  35208. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35209. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35210. };
  35211. // Luminance generator
  35212. HDRRenderingPipeline.LUM_STEPS = 6;
  35213. return HDRRenderingPipeline;
  35214. })(BABYLON.PostProcessRenderPipeline);
  35215. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35216. })(BABYLON || (BABYLON = {}));
  35217. var BABYLON;
  35218. (function (BABYLON) {
  35219. var FaceAdjacencies = (function () {
  35220. function FaceAdjacencies() {
  35221. this.edges = new Array();
  35222. this.edgesConnectedCount = 0;
  35223. }
  35224. return FaceAdjacencies;
  35225. })();
  35226. var EdgesRenderer = (function () {
  35227. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35228. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35229. if (epsilon === void 0) { epsilon = 0.95; }
  35230. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35231. this._linesPositions = new Array();
  35232. this._linesNormals = new Array();
  35233. this._linesIndices = new Array();
  35234. this._buffers = new Array();
  35235. this._checkVerticesInsteadOfIndices = false;
  35236. this._source = source;
  35237. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35238. this._epsilon = epsilon;
  35239. this._prepareRessources();
  35240. this._generateEdgesLines();
  35241. }
  35242. EdgesRenderer.prototype._prepareRessources = function () {
  35243. if (this._lineShader) {
  35244. return;
  35245. }
  35246. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35247. attributes: ["position", "normal"],
  35248. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35249. });
  35250. this._lineShader.disableDepthWrite = true;
  35251. this._lineShader.backFaceCulling = false;
  35252. };
  35253. EdgesRenderer.prototype.dispose = function () {
  35254. this._vb0.dispose();
  35255. this._vb1.dispose();
  35256. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35257. this._lineShader.dispose();
  35258. };
  35259. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35260. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35261. return 0;
  35262. }
  35263. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35264. return 1;
  35265. }
  35266. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35267. return 2;
  35268. }
  35269. return -1;
  35270. };
  35271. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35272. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35273. return 0;
  35274. }
  35275. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35276. return 1;
  35277. }
  35278. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35279. return 2;
  35280. }
  35281. return -1;
  35282. };
  35283. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35284. var needToCreateLine;
  35285. if (edge === undefined) {
  35286. needToCreateLine = true;
  35287. }
  35288. else {
  35289. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35290. needToCreateLine = dotProduct < this._epsilon;
  35291. }
  35292. if (needToCreateLine) {
  35293. var offset = this._linesPositions.length / 3;
  35294. var normal = p0.subtract(p1);
  35295. normal.normalize();
  35296. // Positions
  35297. this._linesPositions.push(p0.x);
  35298. this._linesPositions.push(p0.y);
  35299. this._linesPositions.push(p0.z);
  35300. this._linesPositions.push(p0.x);
  35301. this._linesPositions.push(p0.y);
  35302. this._linesPositions.push(p0.z);
  35303. this._linesPositions.push(p1.x);
  35304. this._linesPositions.push(p1.y);
  35305. this._linesPositions.push(p1.z);
  35306. this._linesPositions.push(p1.x);
  35307. this._linesPositions.push(p1.y);
  35308. this._linesPositions.push(p1.z);
  35309. // Normals
  35310. this._linesNormals.push(p1.x);
  35311. this._linesNormals.push(p1.y);
  35312. this._linesNormals.push(p1.z);
  35313. this._linesNormals.push(-1);
  35314. this._linesNormals.push(p1.x);
  35315. this._linesNormals.push(p1.y);
  35316. this._linesNormals.push(p1.z);
  35317. this._linesNormals.push(1);
  35318. this._linesNormals.push(p0.x);
  35319. this._linesNormals.push(p0.y);
  35320. this._linesNormals.push(p0.z);
  35321. this._linesNormals.push(-1);
  35322. this._linesNormals.push(p0.x);
  35323. this._linesNormals.push(p0.y);
  35324. this._linesNormals.push(p0.z);
  35325. this._linesNormals.push(1);
  35326. // Indices
  35327. this._linesIndices.push(offset);
  35328. this._linesIndices.push(offset + 1);
  35329. this._linesIndices.push(offset + 2);
  35330. this._linesIndices.push(offset);
  35331. this._linesIndices.push(offset + 2);
  35332. this._linesIndices.push(offset + 3);
  35333. }
  35334. };
  35335. EdgesRenderer.prototype._generateEdgesLines = function () {
  35336. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35337. var indices = this._source.getIndices();
  35338. // First let's find adjacencies
  35339. var adjacencies = new Array();
  35340. var faceNormals = new Array();
  35341. var index;
  35342. var faceAdjacencies;
  35343. // Prepare faces
  35344. for (index = 0; index < indices.length; index += 3) {
  35345. faceAdjacencies = new FaceAdjacencies();
  35346. var p0Index = indices[index];
  35347. var p1Index = indices[index + 1];
  35348. var p2Index = indices[index + 2];
  35349. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35350. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35351. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35352. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35353. faceNormal.normalize();
  35354. faceNormals.push(faceNormal);
  35355. adjacencies.push(faceAdjacencies);
  35356. }
  35357. // Scan
  35358. for (index = 0; index < adjacencies.length; index++) {
  35359. faceAdjacencies = adjacencies[index];
  35360. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35361. var otherFaceAdjacencies = adjacencies[otherIndex];
  35362. if (faceAdjacencies.edgesConnectedCount === 3) {
  35363. break;
  35364. }
  35365. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35366. continue;
  35367. }
  35368. var otherP0 = indices[otherIndex * 3];
  35369. var otherP1 = indices[otherIndex * 3 + 1];
  35370. var otherP2 = indices[otherIndex * 3 + 2];
  35371. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35372. var otherEdgeIndex;
  35373. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35374. continue;
  35375. }
  35376. switch (edgeIndex) {
  35377. case 0:
  35378. if (this._checkVerticesInsteadOfIndices) {
  35379. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35380. }
  35381. else {
  35382. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35383. }
  35384. break;
  35385. case 1:
  35386. if (this._checkVerticesInsteadOfIndices) {
  35387. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35388. }
  35389. else {
  35390. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35391. }
  35392. break;
  35393. case 2:
  35394. if (this._checkVerticesInsteadOfIndices) {
  35395. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35396. }
  35397. else {
  35398. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35399. }
  35400. break;
  35401. }
  35402. if (otherEdgeIndex === -1) {
  35403. continue;
  35404. }
  35405. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35406. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35407. faceAdjacencies.edgesConnectedCount++;
  35408. otherFaceAdjacencies.edgesConnectedCount++;
  35409. if (faceAdjacencies.edgesConnectedCount === 3) {
  35410. break;
  35411. }
  35412. }
  35413. }
  35414. }
  35415. // Create lines
  35416. for (index = 0; index < adjacencies.length; index++) {
  35417. // 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
  35418. var current = adjacencies[index];
  35419. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35420. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35421. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35422. }
  35423. // Merge into a single mesh
  35424. var engine = this._source.getScene().getEngine();
  35425. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35426. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35427. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35428. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35429. this._ib = engine.createIndexBuffer(this._linesIndices);
  35430. this._indicesCount = this._linesIndices.length;
  35431. };
  35432. EdgesRenderer.prototype.render = function () {
  35433. if (!this._lineShader.isReady()) {
  35434. return;
  35435. }
  35436. var scene = this._source.getScene();
  35437. var engine = scene.getEngine();
  35438. this._lineShader._preBind();
  35439. // VBOs
  35440. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35441. scene.resetCachedMaterial();
  35442. this._lineShader.setColor4("color", this._source.edgesColor);
  35443. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35444. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35445. this._lineShader.bind(this._source.getWorldMatrix());
  35446. // Draw order
  35447. engine.draw(true, 0, this._indicesCount);
  35448. this._lineShader.unbind();
  35449. engine.setDepthWrite(true);
  35450. };
  35451. return EdgesRenderer;
  35452. })();
  35453. BABYLON.EdgesRenderer = EdgesRenderer;
  35454. })(BABYLON || (BABYLON = {}));
  35455. var BABYLON;
  35456. (function (BABYLON) {
  35457. (function (TonemappingOperator) {
  35458. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35459. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35460. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35461. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35462. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35463. var TonemappingOperator = BABYLON.TonemappingOperator;
  35464. ;
  35465. var TonemapPostProcess = (function (_super) {
  35466. __extends(TonemapPostProcess, _super);
  35467. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35468. var _this = this;
  35469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35470. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35471. this._operator = operator;
  35472. this._exposureAdjustment = exposureAdjustment;
  35473. var params = ["_ExposureAdjustment"];
  35474. var defines = "#define ";
  35475. if (operator === TonemappingOperator.Hable)
  35476. defines += "HABLE_TONEMAPPING";
  35477. else if (operator === TonemappingOperator.Reinhard)
  35478. defines += "REINHARD_TONEMAPPING";
  35479. else if (operator === TonemappingOperator.HejiDawson)
  35480. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35481. else if (operator === TonemappingOperator.Photographic)
  35482. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35483. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35484. this.onApply = function (effect) {
  35485. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35486. };
  35487. }
  35488. return TonemapPostProcess;
  35489. })(BABYLON.PostProcess);
  35490. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35491. })(BABYLON || (BABYLON = {}));
  35492. var BABYLON;
  35493. (function (BABYLON) {
  35494. var maxSimultaneousLights = 4;
  35495. var PBRMaterialDefines = (function (_super) {
  35496. __extends(PBRMaterialDefines, _super);
  35497. function PBRMaterialDefines() {
  35498. _super.call(this);
  35499. this.ALBEDO = false;
  35500. this.CLIPPLANE = false;
  35501. this.ALPHATEST = false;
  35502. this.FOG = false;
  35503. this.NORMAL = false;
  35504. this.UV1 = false;
  35505. this.UV2 = false;
  35506. this.VERTEXCOLOR = false;
  35507. this.VERTEXALPHA = false;
  35508. this.BONES = false;
  35509. this.BONES4 = false;
  35510. this.BonesPerMesh = 0;
  35511. this.INSTANCES = false;
  35512. this.POINTSIZE = false;
  35513. this._keys = Object.keys(this);
  35514. }
  35515. return PBRMaterialDefines;
  35516. })(BABYLON.MaterialDefines);
  35517. var PBRMaterial = (function (_super) {
  35518. __extends(PBRMaterial, _super);
  35519. function PBRMaterial(name, scene) {
  35520. _super.call(this, name, scene);
  35521. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35522. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35523. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35524. this._scaledDiffuse = new BABYLON.Color3();
  35525. this._scaledSpecular = new BABYLON.Color3();
  35526. this._defines = new PBRMaterialDefines();
  35527. this._cachedDefines = new PBRMaterialDefines();
  35528. this._cachedDefines.BonesPerMesh = -1;
  35529. }
  35530. PBRMaterial.prototype.needAlphaBlending = function () {
  35531. return this.alpha < 1.0;
  35532. };
  35533. PBRMaterial.prototype.needAlphaTesting = function () {
  35534. return false;
  35535. };
  35536. PBRMaterial.prototype.getAlphaTestTexture = function () {
  35537. return null;
  35538. };
  35539. // Methods
  35540. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  35541. if (this.checkReadyOnlyOnce) {
  35542. if (this._wasPreviouslyReady) {
  35543. return true;
  35544. }
  35545. }
  35546. var scene = this.getScene();
  35547. if (!this.checkReadyOnEveryCall) {
  35548. if (this._renderId === scene.getRenderId()) {
  35549. return true;
  35550. }
  35551. }
  35552. var engine = scene.getEngine();
  35553. var needNormals = false;
  35554. var needUVs = false;
  35555. this._defines.reset();
  35556. // Textures
  35557. if (scene.texturesEnabled) {
  35558. }
  35559. // Effect
  35560. if (scene.clipPlane) {
  35561. this._defines.CLIPPLANE = true;
  35562. }
  35563. if (engine.getAlphaTesting()) {
  35564. this._defines.ALPHATEST = true;
  35565. }
  35566. // Point size
  35567. if (this.pointsCloud || scene.forcePointsCloud) {
  35568. this._defines.POINTSIZE = true;
  35569. }
  35570. // Fog
  35571. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35572. this._defines.FOG = true;
  35573. }
  35574. // Lights
  35575. // Attribs
  35576. if (mesh) {
  35577. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35578. this._defines.NORMAL = true;
  35579. }
  35580. if (needUVs) {
  35581. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35582. this._defines.UV1 = true;
  35583. }
  35584. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35585. this._defines.UV2 = true;
  35586. }
  35587. }
  35588. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35589. this._defines.VERTEXCOLOR = true;
  35590. if (mesh.hasVertexAlpha) {
  35591. this._defines.VERTEXALPHA = true;
  35592. }
  35593. }
  35594. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35595. this._defines.BONES = true;
  35596. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  35597. this._defines.BONES4 = true;
  35598. }
  35599. // Instances
  35600. if (useInstances) {
  35601. this._defines.INSTANCES = true;
  35602. }
  35603. }
  35604. // Get correct effect
  35605. if (!this._defines.isEqual(this._cachedDefines)) {
  35606. this._defines.cloneTo(this._cachedDefines);
  35607. scene.resetCachedMaterial();
  35608. // Fallbacks
  35609. var fallbacks = new BABYLON.EffectFallbacks();
  35610. if (this._defines.FOG) {
  35611. fallbacks.addFallback(1, "FOG");
  35612. }
  35613. if (this._defines.BONES4) {
  35614. fallbacks.addFallback(0, "BONES4");
  35615. }
  35616. //Attributes
  35617. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35618. if (this._defines.NORMAL) {
  35619. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35620. }
  35621. if (this._defines.UV1) {
  35622. attribs.push(BABYLON.VertexBuffer.UVKind);
  35623. }
  35624. if (this._defines.UV2) {
  35625. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35626. }
  35627. if (this._defines.VERTEXCOLOR) {
  35628. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35629. }
  35630. if (this._defines.BONES) {
  35631. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35632. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35633. }
  35634. if (this._defines.INSTANCES) {
  35635. attribs.push("world0");
  35636. attribs.push("world1");
  35637. attribs.push("world2");
  35638. attribs.push("world3");
  35639. }
  35640. // Legacy browser patch
  35641. var join = this._defines.toString();
  35642. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  35643. "vFogInfos", "vFogColor", "pointSize",
  35644. "mBones",
  35645. "vClipPlane",
  35646. ], [], join, fallbacks, this.onCompiled, this.onError);
  35647. }
  35648. if (!this._effect.isReady()) {
  35649. return false;
  35650. }
  35651. this._renderId = scene.getRenderId();
  35652. this._wasPreviouslyReady = true;
  35653. return true;
  35654. };
  35655. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35656. this._effect.setMatrix("world", world);
  35657. };
  35658. PBRMaterial.prototype.bind = function (world, mesh) {
  35659. var scene = this.getScene();
  35660. // Matrices
  35661. this.bindOnlyWorldMatrix(world);
  35662. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35663. // Bones
  35664. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35665. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35666. }
  35667. if (scene.getCachedMaterial() !== this) {
  35668. // Clip plane
  35669. if (scene.clipPlane) {
  35670. var clipPlane = scene.clipPlane;
  35671. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35672. }
  35673. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  35674. }
  35675. // Point size
  35676. if (this.pointsCloud) {
  35677. this._effect.setFloat("pointSize", this.pointSize);
  35678. }
  35679. // Colors
  35680. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  35681. // View
  35682. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35683. this._effect.setMatrix("view", scene.getViewMatrix());
  35684. }
  35685. // Fog
  35686. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35687. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35688. this._effect.setColor3("vFogColor", scene.fogColor);
  35689. }
  35690. _super.prototype.bind.call(this, world, mesh);
  35691. };
  35692. PBRMaterial.prototype.getAnimatables = function () {
  35693. var results = [];
  35694. return results;
  35695. };
  35696. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  35697. _super.prototype.dispose.call(this, forceDisposeEffect);
  35698. };
  35699. PBRMaterial.prototype.clone = function (name) {
  35700. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  35701. // Base material
  35702. this.copyTo(newPBRMaterial);
  35703. // PBRMaterial material
  35704. newPBRMaterial.albedoColor = this.albedoColor.clone();
  35705. return newPBRMaterial;
  35706. };
  35707. return PBRMaterial;
  35708. })(BABYLON.Material);
  35709. BABYLON.PBRMaterial = PBRMaterial;
  35710. })(BABYLON || (BABYLON = {}));
  35711. var BABYLON;
  35712. (function (BABYLON) {
  35713. var ReflectionProbe = (function () {
  35714. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35715. var _this = this;
  35716. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35717. this.name = name;
  35718. this._viewMatrix = BABYLON.Matrix.Identity();
  35719. this._target = BABYLON.Vector3.Zero();
  35720. this._add = BABYLON.Vector3.Zero();
  35721. this.position = BABYLON.Vector3.Zero();
  35722. this._scene = scene;
  35723. this._scene.reflectionProbes.push(this);
  35724. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35725. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35726. switch (faceIndex) {
  35727. case 0:
  35728. _this._add.copyFromFloats(1, 0, 0);
  35729. break;
  35730. case 1:
  35731. _this._add.copyFromFloats(-1, 0, 0);
  35732. break;
  35733. case 2:
  35734. _this._add.copyFromFloats(0, -1, 0);
  35735. break;
  35736. case 3:
  35737. _this._add.copyFromFloats(0, 1, 0);
  35738. break;
  35739. case 4:
  35740. _this._add.copyFromFloats(0, 0, 1);
  35741. break;
  35742. case 5:
  35743. _this._add.copyFromFloats(0, 0, -1);
  35744. break;
  35745. }
  35746. if (_this._attachedMesh) {
  35747. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35748. }
  35749. _this.position.addToRef(_this._add, _this._target);
  35750. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35751. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35752. };
  35753. this._renderTargetTexture.onAfterUnbind = function () {
  35754. scene.updateTransformMatrix(true);
  35755. };
  35756. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35757. }
  35758. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35759. get: function () {
  35760. return this._renderTargetTexture.refreshRate;
  35761. },
  35762. set: function (value) {
  35763. this._renderTargetTexture.refreshRate = value;
  35764. },
  35765. enumerable: true,
  35766. configurable: true
  35767. });
  35768. ReflectionProbe.prototype.getScene = function () {
  35769. return this._scene;
  35770. };
  35771. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35772. get: function () {
  35773. return this._renderTargetTexture;
  35774. },
  35775. enumerable: true,
  35776. configurable: true
  35777. });
  35778. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35779. get: function () {
  35780. return this._renderTargetTexture.renderList;
  35781. },
  35782. enumerable: true,
  35783. configurable: true
  35784. });
  35785. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35786. this._attachedMesh = mesh;
  35787. };
  35788. ReflectionProbe.prototype.dispose = function () {
  35789. var index = this._scene.reflectionProbes.indexOf(this);
  35790. if (index !== -1) {
  35791. // Remove from the scene if found
  35792. this._scene.reflectionProbes.splice(index, 1);
  35793. }
  35794. };
  35795. return ReflectionProbe;
  35796. })();
  35797. BABYLON.ReflectionProbe = ReflectionProbe;
  35798. })(BABYLON || (BABYLON = {}));
  35799. var BABYLON;
  35800. (function (BABYLON) {
  35801. var SolidParticle = (function () {
  35802. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35803. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35804. this.position = BABYLON.Vector3.Zero(); // position
  35805. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35806. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35807. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35808. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35809. this.alive = true; // alive
  35810. this.idx = particleIndex;
  35811. this._pos = positionIndex;
  35812. this._model = model;
  35813. this.shapeId = shapeId;
  35814. this.idxInShape = idxInShape;
  35815. }
  35816. return SolidParticle;
  35817. })();
  35818. BABYLON.SolidParticle = SolidParticle;
  35819. var ModelShape = (function () {
  35820. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35821. this.shapeID = id;
  35822. this._shape = shape;
  35823. this._shapeUV = shapeUV;
  35824. this._positionFunction = posFunction;
  35825. this._vertexFunction = vtxFunction;
  35826. }
  35827. return ModelShape;
  35828. })();
  35829. BABYLON.ModelShape = ModelShape;
  35830. })(BABYLON || (BABYLON = {}));
  35831. var BABYLON;
  35832. (function (BABYLON) {
  35833. var SolidParticleSystem = (function () {
  35834. function SolidParticleSystem(name, scene, options) {
  35835. // public members
  35836. this.particles = new Array();
  35837. this.nbParticles = 0;
  35838. this.billboard = false;
  35839. this.counter = 0;
  35840. this._positions = new Array();
  35841. this._indices = new Array();
  35842. this._normals = new Array();
  35843. this._colors = new Array();
  35844. this._uvs = new Array();
  35845. this._index = 0; // indices index
  35846. this._updatable = true;
  35847. this._shapeCounter = 0;
  35848. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35849. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35850. this._computeParticleColor = true;
  35851. this._computeParticleTexture = true;
  35852. this._computeParticleRotation = true;
  35853. this._computeParticleVertex = false;
  35854. this._cam_axisZ = BABYLON.Vector3.Zero();
  35855. this._cam_axisY = BABYLON.Vector3.Zero();
  35856. this._cam_axisX = BABYLON.Vector3.Zero();
  35857. this._axisX = BABYLON.Axis.X;
  35858. this._axisY = BABYLON.Axis.Y;
  35859. this._axisZ = BABYLON.Axis.Z;
  35860. this._fakeCamPos = BABYLON.Vector3.Zero();
  35861. this._rotMatrix = new BABYLON.Matrix();
  35862. this._invertedMatrix = new BABYLON.Matrix();
  35863. this._rotated = BABYLON.Vector3.Zero();
  35864. this._quaternion = new BABYLON.Quaternion();
  35865. this._vertex = BABYLON.Vector3.Zero();
  35866. this._yaw = 0.0;
  35867. this._pitch = 0.0;
  35868. this._roll = 0.0;
  35869. this._halfroll = 0.0;
  35870. this._halfpitch = 0.0;
  35871. this._halfyaw = 0.0;
  35872. this._sinRoll = 0.0;
  35873. this._cosRoll = 0.0;
  35874. this._sinPitch = 0.0;
  35875. this._cosPitch = 0.0;
  35876. this._sinYaw = 0.0;
  35877. this._cosYaw = 0.0;
  35878. this.name = name;
  35879. this._scene = scene;
  35880. this._camera = scene.activeCamera;
  35881. if (options && options.updatable) {
  35882. this._updatable = options.updatable;
  35883. }
  35884. else {
  35885. this._updatable = true;
  35886. }
  35887. }
  35888. // build the SPS mesh : returns the mesh
  35889. SolidParticleSystem.prototype.buildMesh = function () {
  35890. if (this.nbParticles === 0) {
  35891. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35892. this.addShape(triangle, 1);
  35893. triangle.dispose();
  35894. }
  35895. this._positions32 = new Float32Array(this._positions);
  35896. this._uvs32 = new Float32Array(this._uvs);
  35897. this._colors32 = new Float32Array(this._colors);
  35898. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35899. this._normals32 = new Float32Array(this._normals);
  35900. var vertexData = new BABYLON.VertexData();
  35901. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35902. vertexData.indices = this._indices;
  35903. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35904. if (this._uvs32) {
  35905. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35906. ;
  35907. }
  35908. if (this._colors32) {
  35909. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35910. }
  35911. var mesh = new BABYLON.Mesh(name, this._scene);
  35912. vertexData.applyToMesh(mesh, this._updatable);
  35913. this.mesh = mesh;
  35914. // free memory
  35915. this._positions = null;
  35916. this._normals = null;
  35917. this._uvs = null;
  35918. this._colors = null;
  35919. if (!this._updatable) {
  35920. this.particles.length = 0;
  35921. }
  35922. return mesh;
  35923. };
  35924. //reset copy
  35925. SolidParticleSystem.prototype._resetCopy = function () {
  35926. this._copy.position.x = 0;
  35927. this._copy.position.y = 0;
  35928. this._copy.position.z = 0;
  35929. this._copy.rotation.x = 0;
  35930. this._copy.rotation.y = 0;
  35931. this._copy.rotation.z = 0;
  35932. this._copy.quaternion = null;
  35933. this._copy.scale.x = 1;
  35934. this._copy.scale.y = 1;
  35935. this._copy.scale.z = 1;
  35936. this._copy.uvs.x = 0;
  35937. this._copy.uvs.y = 0;
  35938. this._copy.uvs.z = 1;
  35939. this._copy.uvs.w = 1;
  35940. this._copy.color = null;
  35941. };
  35942. // _meshBuilder : inserts the shape model in the global SPS mesh
  35943. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35944. var i;
  35945. var u = 0;
  35946. var c = 0;
  35947. this._resetCopy();
  35948. if (options && options.positionFunction) {
  35949. options.positionFunction(this._copy, idx, idxInShape);
  35950. }
  35951. if (this._copy.quaternion) {
  35952. this._quaternion.x = this._copy.quaternion.x;
  35953. this._quaternion.y = this._copy.quaternion.y;
  35954. this._quaternion.z = this._copy.quaternion.z;
  35955. this._quaternion.w = this._copy.quaternion.w;
  35956. }
  35957. else {
  35958. this._yaw = this._copy.rotation.y;
  35959. this._pitch = this._copy.rotation.x;
  35960. this._roll = this._copy.rotation.z;
  35961. this._quaternionRotationYPR();
  35962. }
  35963. this._quaternionToRotationMatrix();
  35964. for (i = 0; i < shape.length; i++) {
  35965. this._vertex.x = shape[i].x;
  35966. this._vertex.y = shape[i].y;
  35967. this._vertex.z = shape[i].z;
  35968. if (options && options.vertexFunction) {
  35969. options.vertexFunction(this._copy, this._vertex, i);
  35970. }
  35971. this._vertex.x *= this._copy.scale.x;
  35972. this._vertex.y *= this._copy.scale.y;
  35973. this._vertex.z *= this._copy.scale.z;
  35974. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35975. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35976. if (meshUV) {
  35977. 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);
  35978. u += 2;
  35979. }
  35980. if (this._copy.color) {
  35981. this._color = this._copy.color;
  35982. }
  35983. else if (meshCol && meshCol[c]) {
  35984. this._color.r = meshCol[c];
  35985. this._color.g = meshCol[c + 1];
  35986. this._color.b = meshCol[c + 2];
  35987. this._color.a = meshCol[c + 3];
  35988. }
  35989. else {
  35990. this._color.r = 1;
  35991. this._color.g = 1;
  35992. this._color.b = 1;
  35993. this._color.a = 1;
  35994. }
  35995. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35996. c += 4;
  35997. }
  35998. for (i = 0; i < meshInd.length; i++) {
  35999. indices.push(p + meshInd[i]);
  36000. }
  36001. };
  36002. // returns a shape array from positions array
  36003. SolidParticleSystem.prototype._posToShape = function (positions) {
  36004. var shape = [];
  36005. for (var i = 0; i < positions.length; i += 3) {
  36006. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36007. }
  36008. return shape;
  36009. };
  36010. // returns a shapeUV array from a Vector4 uvs
  36011. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36012. var shapeUV = [];
  36013. if (uvs) {
  36014. for (var i = 0; i < uvs.length; i++)
  36015. shapeUV.push(uvs[i]);
  36016. }
  36017. return shapeUV;
  36018. };
  36019. // adds a new particle object in the particles array
  36020. SolidParticleSystem.prototype._addParticle = function (p, idxpos, model, shapeId, idxInShape) {
  36021. this.particles.push(new BABYLON.SolidParticle(p, idxpos, model, shapeId, idxInShape));
  36022. };
  36023. // add solid particles from a shape model in the particles array
  36024. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36025. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36026. var meshInd = mesh.getIndices();
  36027. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36028. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36029. var shape = this._posToShape(meshPos);
  36030. var shapeUV = this._uvsToShapeUV(meshUV);
  36031. var posfunc = options ? options.positionFunction : null;
  36032. var vtxfunc = options ? options.vertexFunction : null;
  36033. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36034. // particles
  36035. for (var i = 0; i < nb; i++) {
  36036. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, this.nbParticles + i, i, options);
  36037. if (this._updatable) {
  36038. this._addParticle(this.nbParticles + i, this._positions.length, modelShape, this._shapeCounter, i);
  36039. }
  36040. this._index += shape.length;
  36041. }
  36042. this.nbParticles += nb;
  36043. this._shapeCounter++;
  36044. return this._shapeCounter;
  36045. };
  36046. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36047. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36048. this._resetCopy();
  36049. if (particle._model._positionFunction) {
  36050. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36051. }
  36052. if (this._copy.quaternion) {
  36053. this._quaternion.x = this._copy.quaternion.x;
  36054. this._quaternion.y = this._copy.quaternion.y;
  36055. this._quaternion.z = this._copy.quaternion.z;
  36056. this._quaternion.w = this._copy.quaternion.w;
  36057. }
  36058. else {
  36059. this._yaw = this._copy.rotation.y;
  36060. this._pitch = this._copy.rotation.x;
  36061. this._roll = this._copy.rotation.z;
  36062. this._quaternionRotationYPR();
  36063. }
  36064. this._quaternionToRotationMatrix();
  36065. this._shape = particle._model._shape;
  36066. for (var pt = 0; pt < this._shape.length; pt++) {
  36067. this._vertex.x = this._shape[pt].x;
  36068. this._vertex.y = this._shape[pt].y;
  36069. this._vertex.z = this._shape[pt].z;
  36070. if (particle._model._vertexFunction) {
  36071. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36072. }
  36073. this._vertex.x *= this._copy.scale.x;
  36074. this._vertex.y *= this._copy.scale.y;
  36075. this._vertex.z *= this._copy.scale.z;
  36076. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36077. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36078. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36079. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36080. }
  36081. particle.position.x = 0;
  36082. particle.position.y = 0;
  36083. particle.position.z = 0;
  36084. particle.rotation.x = 0;
  36085. particle.rotation.y = 0;
  36086. particle.rotation.z = 0;
  36087. particle.quaternion = null;
  36088. particle.scale.x = 1;
  36089. particle.scale.y = 1;
  36090. particle.scale.z = 1;
  36091. };
  36092. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36093. SolidParticleSystem.prototype.rebuildMesh = function () {
  36094. for (var p = 0; p < this.particles.length; p++) {
  36095. this._rebuildParticle(this.particles[p]);
  36096. }
  36097. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36098. };
  36099. // sets all the particles : updates the VBO
  36100. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36101. if (start === void 0) { start = 0; }
  36102. if (end === void 0) { end = this.nbParticles - 1; }
  36103. if (update === void 0) { update = true; }
  36104. // custom beforeUpdate
  36105. this.beforeUpdateParticles(start, end, update);
  36106. this._cam_axisX.x = 1;
  36107. this._cam_axisX.y = 0;
  36108. this._cam_axisX.z = 0;
  36109. this._cam_axisY.x = 0;
  36110. this._cam_axisY.y = 1;
  36111. this._cam_axisY.z = 0;
  36112. this._cam_axisZ.x = 0;
  36113. this._cam_axisZ.y = 0;
  36114. this._cam_axisZ.z = 1;
  36115. // if the particles will always face the camera
  36116. if (this.billboard) {
  36117. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36118. this._yaw = this.mesh.rotation.y;
  36119. this._pitch = this.mesh.rotation.x;
  36120. this._roll = this.mesh.rotation.z;
  36121. this._quaternionRotationYPR();
  36122. this._quaternionToRotationMatrix();
  36123. this._rotMatrix.invertToRef(this._invertedMatrix);
  36124. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertedMatrix, this._fakeCamPos);
  36125. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36126. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36127. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36128. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36129. this._cam_axisY.normalize();
  36130. this._cam_axisX.normalize();
  36131. this._cam_axisZ.normalize();
  36132. }
  36133. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36134. var idx = 0;
  36135. var index = 0;
  36136. var colidx = 0;
  36137. var colorIndex = 0;
  36138. var uvidx = 0;
  36139. var uvIndex = 0;
  36140. // particle loop
  36141. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36142. for (var p = start; p <= end; p++) {
  36143. this._particle = this.particles[p];
  36144. this._shape = this._particle._model._shape;
  36145. this._shapeUV = this._particle._model._shapeUV;
  36146. // call to custom user function to update the particle properties
  36147. this.updateParticle(this._particle);
  36148. // particle rotation matrix
  36149. if (this.billboard) {
  36150. this._particle.rotation.x = 0.0;
  36151. this._particle.rotation.y = 0.0;
  36152. }
  36153. if (this._computeParticleRotation) {
  36154. if (this._particle.quaternion) {
  36155. this._quaternion.x = this._particle.quaternion.x;
  36156. this._quaternion.y = this._particle.quaternion.y;
  36157. this._quaternion.z = this._particle.quaternion.z;
  36158. this._quaternion.w = this._particle.quaternion.w;
  36159. }
  36160. else {
  36161. this._yaw = this._particle.rotation.y;
  36162. this._pitch = this._particle.rotation.x;
  36163. this._roll = this._particle.rotation.z;
  36164. this._quaternionRotationYPR();
  36165. }
  36166. this._quaternionToRotationMatrix();
  36167. }
  36168. for (var pt = 0; pt < this._shape.length; pt++) {
  36169. idx = index + pt * 3;
  36170. colidx = colorIndex + pt * 4;
  36171. uvidx = uvIndex + pt * 2;
  36172. this._vertex.x = this._shape[pt].x;
  36173. this._vertex.y = this._shape[pt].y;
  36174. this._vertex.z = this._shape[pt].z;
  36175. if (this._computeParticleVertex) {
  36176. this.updateParticleVertex(this._particle, this._vertex, pt);
  36177. }
  36178. this._vertex.x *= this._particle.scale.x;
  36179. this._vertex.y *= this._particle.scale.y;
  36180. this._vertex.z *= this._particle.scale.z;
  36181. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36182. 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;
  36183. 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;
  36184. 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;
  36185. if (this._computeParticleColor) {
  36186. this._colors32[colidx] = this._particle.color.r;
  36187. this._colors32[colidx + 1] = this._particle.color.g;
  36188. this._colors32[colidx + 2] = this._particle.color.b;
  36189. this._colors32[colidx + 3] = this._particle.color.a;
  36190. }
  36191. if (this._computeParticleTexture) {
  36192. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36193. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36194. }
  36195. }
  36196. index = idx + 3;
  36197. colorIndex = colidx + 4;
  36198. uvIndex = uvidx + 2;
  36199. }
  36200. if (update) {
  36201. if (this._computeParticleColor) {
  36202. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36203. }
  36204. if (this._computeParticleTexture) {
  36205. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36206. }
  36207. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36208. if (!this.mesh.areNormalsFrozen) {
  36209. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36210. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36211. }
  36212. }
  36213. this.afterUpdateParticles(start, end, update);
  36214. };
  36215. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36216. this._halfroll = this._roll * 0.5;
  36217. this._halfpitch = this._pitch * 0.5;
  36218. this._halfyaw = this._yaw * 0.5;
  36219. this._sinRoll = Math.sin(this._halfroll);
  36220. this._cosRoll = Math.cos(this._halfroll);
  36221. this._sinPitch = Math.sin(this._halfpitch);
  36222. this._cosPitch = Math.cos(this._halfpitch);
  36223. this._sinYaw = Math.sin(this._halfyaw);
  36224. this._cosYaw = Math.cos(this._halfyaw);
  36225. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36226. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36227. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36228. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36229. };
  36230. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36231. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36232. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36233. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36234. this._rotMatrix.m[3] = 0;
  36235. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36236. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36237. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36238. this._rotMatrix.m[7] = 0;
  36239. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36240. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36241. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36242. this._rotMatrix.m[11] = 0;
  36243. this._rotMatrix.m[12] = 0;
  36244. this._rotMatrix.m[13] = 0;
  36245. this._rotMatrix.m[14] = 0;
  36246. this._rotMatrix.m[15] = 1.0;
  36247. };
  36248. // dispose the SPS
  36249. SolidParticleSystem.prototype.dispose = function () {
  36250. this.mesh.dispose();
  36251. // drop references to internal big arrays for the GC
  36252. this._positions = null;
  36253. this._indices = null;
  36254. this._normals = null;
  36255. this._uvs = null;
  36256. this._colors = null;
  36257. this._positions32 = null;
  36258. this._normals32 = null;
  36259. this._uvs32 = null;
  36260. this._colors32 = null;
  36261. };
  36262. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36263. // getters
  36264. get: function () {
  36265. return this._computeParticleRotation;
  36266. },
  36267. // Optimizer setters
  36268. set: function (val) {
  36269. this._computeParticleRotation = val;
  36270. },
  36271. enumerable: true,
  36272. configurable: true
  36273. });
  36274. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36275. get: function () {
  36276. return this._computeParticleColor;
  36277. },
  36278. set: function (val) {
  36279. this._computeParticleColor = val;
  36280. },
  36281. enumerable: true,
  36282. configurable: true
  36283. });
  36284. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36285. get: function () {
  36286. return this._computeParticleTexture;
  36287. },
  36288. set: function (val) {
  36289. this._computeParticleTexture = val;
  36290. },
  36291. enumerable: true,
  36292. configurable: true
  36293. });
  36294. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36295. get: function () {
  36296. return this._computeParticleVertex;
  36297. },
  36298. set: function (val) {
  36299. this._computeParticleVertex = val;
  36300. },
  36301. enumerable: true,
  36302. configurable: true
  36303. });
  36304. // =======================================================================
  36305. // Particle behavior logic
  36306. // these following methods may be overwritten by the user to fit his needs
  36307. // init : sets all particles first values and calls updateParticle to set them in space
  36308. // can be overwritten by the user
  36309. SolidParticleSystem.prototype.initParticles = function () {
  36310. };
  36311. // recycles a particle : can by overwritten by the user
  36312. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36313. return particle;
  36314. };
  36315. // updates a particle : can be overwritten by the user
  36316. // will be called on each particle by setParticles() :
  36317. // ex : just set a particle position or velocity and recycle conditions
  36318. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36319. return particle;
  36320. };
  36321. // updates a vertex of a particle : can be overwritten by the user
  36322. // will be called on each vertex particle by setParticles() :
  36323. // particle : the current particle
  36324. // vertex : the current index of the current particle
  36325. // pt : the index of the current vertex in the particle shape
  36326. // ex : just set a vertex particle position
  36327. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36328. return vertex;
  36329. };
  36330. // will be called before any other treatment by setParticles()
  36331. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36332. };
  36333. // will be called after all setParticles() treatments
  36334. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36335. };
  36336. return SolidParticleSystem;
  36337. })();
  36338. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36339. })(BABYLON || (BABYLON = {}));
  36340. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"precision highp float;\r\n\r\n// Constants\r\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\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\tbias = vReflectionInfos.y;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform 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\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"precision highp float;\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\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#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#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;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#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 bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = 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, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  36341. 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={}));";
  36342. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36343. module.exports = BABYLON;
  36344. };